[R] evaluating and walking in names

Thomas Lumley tlumley at u.washington.edu
Thu Aug 7 05:42:59 CEST 2003


On Wed, 6 Aug 2003 Ted.Harding at nessie.mcc.ac.uk wrote:

> QUESTION TO EXPERTS:
> While (a construction I've often used successfully):
>
>   for(Z in c("X1","X2","X3")){
>     Z<-eval(as.name(Z))
>     do.something.with(Z) }
>
> works, going through the variables named "X1", "X2", "X3" in
> turn, when I was trying to clean up Cezar's example above I found
> that if you construct the name Z by pasting so that it comes to
> "my.data$X1" then the object "my.data$X1" is not found. Presumably
> this is because the "$" operator is not functional in this context,
> but I can't locate an explanation of this. Can anyone elucidate?

Because as.name() converts the string to a name, but you wanted an
expression (the X1 component of my.data).

In r-devel this is visually clearer
> as.name("my.data$X1")
`my.data$X1`
the backticks indicating a syntatically weird name.  You can  do eg
> `my.data$X1` <- 42
> eval(as.name("my.data$X1"))
[1] 42
In current R versions you would have to use
assign("mydata$X1", 42)
to assign to this variable.

To get the X1 component of my.data you would need
eval(parse(text="my.data$X1"))
> my.data<-data.frame(X1=1:2,X2=2:3)
> parse(text="my.data$X1")
expression(my.data$X1)
> eval(parse(text="my.data$X1"))
[1] 1 2

	-thomas




More information about the R-help mailing list