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