[R] question on 'within' and 'parse' commands

Romain Francois romain.francois at dbmail.com
Thu Jan 7 09:27:27 CET 2010


Hello,

parse just parse the text into an expression.

 > parse(text="a<-a*10; b<-2:6")
expression(a<-a*10, b<-2:6)
attr(,"srcfile")
<text>

If you want to evaluate the expression, you need to call eval

 > y <- within(x, eval(parse(text="a<-a*10; b<-2:6")))
 > y
    a b
1 10 2
2 20 3
3 30 4
4 40 5
5 50 6

Or you can just do this :

 > y <- within(x, { a<-a*10; b<-2:6 } )
 > y
    a b
1 10 2
2 20 3
3 30 4
4 40 5
5 50 6

Romain


On 01/07/2010 09:08 AM, N Klepeis wrote:
>
> Hi,
>
> Why can't I pass an expression to `within' by way of textual input to
> the 'parse' function?
>
> e.g.,
>
>  > x <- data.frame(a=1:5,b=LETTERS[1:5])
>  > x
> a b
> 1 1 A
> 2 2 B
> 3 3 C
> 4 4 D
> 5 5 E
>  > within(x, parse(text="a<-a*10; b<-2:6"))
> a b
> 1 1 A
> 2 2 B
> 3 3 C
> 4 4 D
> 5 5 E
>  > within(x, parse(text="a<-a*10; b<-2:6")[[1]])
> a b
> 1 1 A
> 2 2 B
> 3 3 C
> 4 4 D
> 5 5 E
>
> This would be very useful to allow for arbitrary evaluation of
> multi-line commands at runtime.
>
> Of course, I can edit the 'within.data.frame' function as follows, but
> isn't there some way to make 'within' more generally like the 'eval'
> command?
>
> alternative:
>
> within.data.frame <-
> function (data, textCMD, ...)
> {
> parent <- parent.frame()
> e <- evalq(environment(), data, parent)
> eval(parse(text=textCMD), e) # used to be eval(substitute(expr), e)
> l <- as.list(e)
> l <- l[!sapply(l, is.null)]
> nD <- length(del <- setdiff(names(data), (nl <- names(l))))
> data[nl] <- l
> if (nD)
> data[del] <- if (nD == 1)
> NULL
> else vector("list", nD)
> data
> }
>
>
> --Neil


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/JFqa : R Journal, Volume 1/2, December 2009
|- http://tr.im/IW9B : C++ exceptions at the R level
`- http://tr.im/IlMh : CPP package: exposing C++ objects



More information about the R-help mailing list