[R] evaluating and walking in names

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Wed Aug 6 23:41:45 CEST 2003


On 06-Aug-03 Cezar Augusto de Freitas Anselmo wrote:
> Hi, all.
> Suppose I have an object with names (like a data.frame) and
> I want to walk in a loop with your names. How can I do this?
> The idea is like this:
> 
> my.data<-data.frame(matrix(runif(6),ncol=2))
> names(my.data)
> [1] "X1" "X2"
> for(i in names(my.data)){
>       my.variable <- cat(paste("my.data$", i, "\n", sep=""))
>       print(mean(my.variable))
> }
>#it doesn't work.

Hi Cezar,

First of all, you should get rid of those "\n" -- they intrude:
> for(i in names(my.data)){ print(paste("my.data$", i, "\n", sep=""))}
[1] "my.data$X1\n"
[1] "my.data$X2\n"
> for(i in names(my.data)){ print(paste("my.data$", i, sep=""))}
[1] "my.data$X1"
[1] "my.data$X2"

Second, you don't need to do the above anyway: the simplest way to
refer to the variable with the name name is simply to index the column
by name:

> for(i in names(my.data)){
      my.variable<-my.data[,i];print(mean(my.variable))}
[1] 0.3302733
[1] 0.6119088

To see this, have a look at

  my.data[,"X1"]
  my.data[,"X2"]

I hope this breaks the block!

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?

Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 06-Aug-03                                       Time: 22:41:45
------------------------------ XFMail ------------------------------




More information about the R-help mailing list