[R] select different variables from a list of data frames

Rui Barradas ruipbarradas at sapo.pt
Tue Nov 13 00:29:30 CET 2012


Hello,

Try the following.

lapply(mylist, function(x) x[,grep("a|q", names(x))])

Hope this helps,

Rui Barradas
Em 12-11-2012 22:34, Simon Kiss escreveu:
> Hi:
> How do I select different variables from a list of data frames.
> I have a list of 13 that looks like below.  Each data frame has more variables than I need.  How do I go through the list and select the variables that I need.
> In the example below, I need to get the variables "a", and "q10" and "q14" to be returned to two separate data frames.
> Thank you.
> Yours, Simon Kiss
>
> #####Sample data
>    mylist<-list(df1=data.frame(a=seq(1,10,1), c=seq(1,109,1), q10=rep('favour', 10)), df2=data.frame(a=seq(1,10,1), b=seq(15,24,1), q14=rep('favour', 10)))
>
> #The variables with different names that I need are
> q<-c('q10', 'q14')
> #My current code
>
> dat<-mapply(function(x,y) {
>    data.frame(a=x$a, y$q)
> }, x=mylist, y=q)
>
> ______________________________________________
> R-help at r-project.org 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.




More information about the R-help mailing list