Skip to content

question on 'within' and 'parse' commands

2 messages · N Klepeis, Romain Francois

#
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
#
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: