tags:

views:

35

answers:

2

A colleague asked me the following question the other day. In the following piece of code, how do you extract the gradient:

> x=5
> a = eval(deriv(~ x^3, "x"))
> a
[1] 125
attr(,"gradient")
      x
[1,] 75

My answer was

>  attr(a, "gradient")[1]
[1] 75

This syntax seems clunky to me. Is there a better way of extracting the gradient?

+2  A: 

Not sure these count as better, but:

with(attributes(a), gradient)

or

attributes(a)$gradient

are alternatives that return the attributes as a list from which to select.

Gavin Simpson
+2  A: 

Though it is no better than your method, you could make a function, grad, that takes a numeric with a gradient attribute and returns the gradient value.

grad = function(x)attr(x,"gradient")[1]

grad(a)

which is now reusable.

Greg