[R] evaluating and walking in names

Jason Turner jasont at indigoindustrial.co.nz
Wed Aug 6 23:33:12 CEST 2003


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.
> 
> Thnaks for all,
> C.
> 
> ========================================
> Cezar Freitas (ICQ 109128967)
> IMECC - UNICAMP
> Campinas, SP - Brasil
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 
> 

You want assign().

df <- data.frame(matrix(runif(20),ncol=2))

# using ii instead of i makes searches *much* easier with
# a text editor.
for(ii in names(df)) {
   assign(ii,df[[ii]])
}

ls()
[1] "X1" "X2" "df" "ii"

# might not be exactly the same on your machine due
# to floating point rounding.
all.equal(X1,df$X1)
[1] TRUE

all.equal(X2,df$X2)
[1] TRUE

Cheers

Jason
-- 
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz




More information about the R-help mailing list