[R] -> using eval(parse(text= ... ))
Duncan Murdoch
murdoch at stats.uwo.ca
Sat Feb 17 03:03:38 CET 2007
On 2/16/2007 7:13 PM, Jon Minton wrote:
> Hi,
>
> I'm unsure why I can't use eval(parse(text=...)) to represent the thing I
> want to assign a value into.
>
> e.g.
>
>> A <- c("Good")
>> B <- c("Bad")
>> C <- c()
>> X <- c("A", "B", "C")
>> eval(parse(text=X[1]))
> [1] "Good"
>> eval(parse(text=X[2])) -> Z
>> Z
> [1] "Bad"
>> eval(parse(text=X[3])) <- "Ugly"
> Error in file(file, "r") : unable to open connection
> In addition: Warning message:
> cannot open file 'C', reason 'No such file or directory'
>
> Why the error message?
>
> I've tried looking through the archive for a solution but, perhaps because
> I'm not too sure how to phrase this problem, I've not found one...
eval(parse(text=X[3])) is asking R to evaluate the expression C, which
doesn't exist yet. The expression
C <- "Ugly"
doesn't evaluate C first (because C doesn't exist yet). It evaluates a
call to "<-" with C as one of the arguments, and "<-" treats that
argument as a name.
There are several things that would work to do what you want, but the
most straightforward is
assign(X[3], "Ugly")
Duncan Murdoch
More information about the R-help
mailing list