Skip to content

Force a variable substitution in expression

3 messages · Duncan Murdoch, Saptarshi Guha

#
Hello,
I have a function that creates an expression object with some variables
substituted e.g

foo <- function(s){
  expression({
    v <- s
    print(v)
  })
}

Thus foo returns an expression, however the expression has the symbol 's'
contained within it and thus returns an error when eval'd e.g

x <- foo(10)
eval(x)
Error in eval(expr, envir, enclos) : object 's' not found

Q: How do I force a substitution so that the returned expression has the value
of 's' 'hardcoded'  in it e.g
returns

expression({
  v <- 10
  print(v)
})

Regards
Saptarshi

----------
saptarshi guha | http://www.stat.purdue.edu/~sguha
It is when I struggle to be brief that I become obscure.
		-- Quintus Horatius Flaccus (Horace)
#
On 27/11/2009 11:04 AM, Saptarshi Guha wrote:
The substitute() function can do it, but the bquote() function is the 
most convenient:

 > foo <- function(s) {
+   bquote(expression({
+    v <- .(s)
+    print(v)
+   }))
+ }
 > foo(10)
expression({
    v <- 10
    print(v)
})

Duncan Murdoch
#
Thanks, after sending this email, i used substitute, but first eval'ing
the formals (since they are delayed assignments).
I see bquote does this for me.


Regards
Saptarshi