[R] select different variables from a list of data frames
arun
smartpink111 at yahoo.com
Tue Nov 13 02:56:50 CET 2012
Hi,
In addition to:
mylist<-list(df1=data.frame(a=seq(1,10,1), c=seq(1,10,1), q10=rep('favour', 10)), df2=data.frame(a=seq(1,10,1), b=seq(15,24,1), q14=rep('favour', 10)))
lapply(mylist,function(x) x[colnames(x)%in% c("a","q10","q14")])
you could also use: lapply(seq_along(mylist),function(i) mylist[[i]][names(mylist[[i]])%in% c("a","q10","q14")])
#[[1]]
# a q10
#1 1 favour
#2 2 favour
#3 3 favour
#4 4 favour
#5 5 favour
#6 6 favour
#7 7 favour
#8 8 favour
#9 9 favour
#10 10 favour
#[[2]]
# a q14
#1 1 favour
#2 2 favour
#3 3 favour
#4 4 favour
#5 5 favour
#6 6 favour
#7 7 favour
#8 8 favour
#9 9 favour
#10 10 favour
A.K.
----- Original Message -----
From: Simon Kiss <sjkiss at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Monday, November 12, 2012 5:34 PM
Subject: [R] select different variables from a list of data frames
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