R difference between expression and as.expression

Well, here is 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 a different result? I believe that R handles these things a little differently, and I want to understand how exactly. A guide to R in which such nuances are covered, if you know one, is also very welcome.

+5
source share
1 answer

If you define x as a number in the global environment, when using as.expression(x^2) function will try to convert the contents of x , not its name, into an expression.

Cm:

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

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

+3
source

Source: https://habr.com/ru/post/1238818/


All Articles