Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R difference between expression and as.expression

Tags:

r

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.

like image 606
ephemeris Avatar asked Oct 18 '22 19:10

ephemeris


1 Answers

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.

like image 113
Carlos Cinelli Avatar answered Nov 18 '22 03:11

Carlos Cinelli