开发者

Extract the gradient from the deriv command

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

开发者_Python百科> 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜