Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

r - For loop to subset a list of dataframes

I have a list of dataframes:

df1<-data.frame("A"=1:10, "B"=c("Mark","John","Lucas","Helen","Rachel","Leyla","Tina","Fanny","Emma","Kate"),"C"=c(91:100))
df2<-data.frame("A"=1:8, "B"=c("Mark","John","Lucas","Helen","Rachel","Leyla","Tina","Fanny"),"C"=c(93:100))
df3<-data.frame("A"=1:3, "B"=c("Mark","John","Lucas"),"C"=c(98:100))
all_df<-list(df1,df2,df3)

And I would like to create a new list of dataframes subsetted by column, like this:

df1_sub<-df1[,c("B","C")]
df2_sub<-df1[,c("B","C")]
df3_sub<-df1[,c("B","C")]
all_df_sub<-list(df1_sub,df2_sub,df3_sub)

Finally assigning to each new dataframe its name:

mynames<-c("df1_sub","df2_sub","df3_sub")
names(all_df_sub)<-mynames

I would like to do this using lapply and a for loop, but I could not figure out how, as I get stuck somewhere in between defining the function and subsetting the list of dataframes (I am not very confident with this, I checked older similar questions without success). This is what I am trying so far:

all_df_sub<-lapply(all_df, function(all_df){
  for([[i]] in all_df) {
    a<-[[i]][,c("B","C")]
    } 
  all_df } )

Any suggestion would be greatly appreciated. Thanks!

question from:https://stackoverflow.com/questions/65844189/for-loop-to-subset-a-list-of-dataframes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try this:

all_df_sub <-lapply(all_df, function(dat){dat[2:3]})
all_df_sub <-setNames(all_df_sub, c("df1_sub","df2_sub","df3_sub"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...