[R] eval(expr) without printing to screen?

hadley wickham h.wickham at gmail.com
Mon Sep 21 00:34:39 CEST 2009


> Here is a simpler mockup which shows the issue:
>
> x = data.frame(rbind(c(1,2,3),c(1,2,3)))
> xnames = c("a", "b", "c")
> names(x) = xnames
>
> for(i in 1:length(x))
> {
> # Create a varying string expression
> expr = paste("y = x$", xnames[i], "[1]", sep="")
>
> # evaluate expression
> eval(parse(text=print(expr)))
>
> # This command prints the expression to screen even when embedded in a
> function in a sourced script.  I would prefer it didn't!
> }

Why are you using eval?  The following is equivalent:

for(name in names(x)) {
  y <- x[[name]][1]
}

Hadley

-- 
http://had.co.nz/




More information about the R-help mailing list