ephemeris
ephemeris

Reputation: 785

R difference between expression and as.expression

Well, here's what I do:

D(expression(x^2),"x")
# 2 * x
D(as.expression(x^2),"x")
# [1] 0
class(as.expression(x^2))
# [1] "expression"
class(expression(x^2))
# [1] "expression"

So, why the different result? I guess R handles those things slightly differently, and I want to understand how exactly. A manual on R where such nuances are covered, if you know one, is also very welcome.

Upvotes: 5

Views: 1003

Answers (1)

Carlos Cinelli
Carlos Cinelli

Reputation: 11607

If you have defined x as number in the global environment, when you use as.expression(x^2) the function will try to convert the content of x and not its name to an expression.

See:

x = 1
as.expression(x^2)
# expression(1)

So when you run D(as.expression(x^2), "x") you are actually running D(expression(1), "x") which is zero.

Upvotes: 3

Related Questions