[R] recovering collums of DF using a text var.list

Petr Klasterecky klaster at karlin.mff.cuni.cz
Sat Feb 24 22:08:30 CET 2007


Milton Cezar Ribeiro napsal(a):
> Hello people,
> 
> I would like to know how can I use a list of variables (a char list) to have access to the collums from a dataframe to be used in some analysis like, just as example, a ploting task on a "for()" loop. Of course the code below is just to understand the way. In this example I have a dataframe with several collumns (more then fifty in my case) and I would like do use only some of them. I really need use a "var.list"! 
> 
> a<-seq(1,100,1)
> b<-c(rep(c(1,2,3,4,5),20))
> c<-rnorm(100,0,1)
> d<-runif(100,0,1)
> e<-c^2
> f<-c/d
> g<-c-d
> df<-data.frame(cbind(a,b,c,d,e,f,g))
> var.list<-c("c","f","g")
> for (myvar in var.list) 
>  {
>  plot(density(df$myvar))   # here I need recover df$c , df$f and df$g
>  }
> 
> Kind regards
> Miltinho 
> Brazil
> 
> __________________________________________________
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

Is this what you expect?
for (myvar in var.list) {
plot(density(df[[paste(myvar)]]), main=paste('Density of',myvar))
}

It may not be bad idea to make a structure (list, dataframe) consisting 
of only those variables you want and use some variant of apply() instead 
of the for-loop. See ?apply, ?tapply, ?sapply

Petr
-- 
Petr Klasterecky
Dept. of Probability and Statistics
Charles University in Prague
Czech Republic



More information about the R-help mailing list