[R] question on 'within' and 'parse' commands
N Klepeis
lists1 at exposurescience.org
Thu Jan 7 09:08:07 CET 2010
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
More information about the R-help
mailing list