I want to evaluate f with the mean=7
mean=7
f <- expression(-(x-mean)^2/2)
then get a new expression:
-(x-7)^2/2
How could I do it? Thanks.
Here is one way.
f <- as.call(f)
eval(substitute(substitute(expr, list(mean=7)), list(expr= f)))
# -(x - 7)^2/2()
If that construction feels mind-bending, you don't need to feel alone: even the guys who wrote the R manual call the problem you've posed here "a puzzle".
f<-quote(-(x-mean)^2/2)) is probably a better way of specifying the expression... as.call won't work on expression(mean)...f needs to be a call rather than an expression, so I guess I'm not quite "there" yet ;)How about gsub?
avg <- 7
f <- expression(-(x-avg)^2/2)
f.new <- as.expression(gsub('avg',avg,f))
expression("-(x - 7)^2/2")
on a side note, you should avoid defining variables with names like mean or data since they are built in R functions.
gsub, ensure the string you are replacing is unique and not a sub-string of something else.In S-Plus, the substitute function has an extra evaluate argument, so there it is rather easy. Unfortunately, R is missing that argument...
# in S-Plus:
x <- expression(-(x-mean)^2/2)
substitute(x, list(mean=7), evaluate=TRUE)
#-(x - 7)^2/2
...so you must resort to something like what @JoshO'Brien suggests. Consider logging this as a feature request with R core ;-)