2

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.

0

3 Answers 3

2

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".

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Nice use of substitute twice. But f<-quote(-(x-mean)^2/2)) is probably a better way of specifying the expression... as.call won't work on expression(mean)...
@Tommy -- Yeah, I thought of making that suggestion, and am glad you brought it up here in comments. I figured that even what's up there is a ton to chew on. It feels like a koan to me -- short, pithy, and still rewarding after hours of contemplation. I don't yet get why f needs to be a call rather than an expression, so I guess I'm not quite "there" yet ;)
0

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.

3 Comments

Thanks. My expression is very long, and there are lots of variables. I will try your method.
I think @JoshO'Brien has a better approach. But if you use gsub, ensure the string you are replacing is unique and not a sub-string of something else.
@Tommy (+1 to Josh) I'd be inclined to agree.
0

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 ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.