开发者

R: combine lists of interest

开发者 https://www.devze.com 2023-03-13 10:32 出处:网络
I have a list like df_all (see below). A = matrix( ce开发者_Python百科iling(10*runif(8)), nrow=4)

I have a list like df_all (see below).

A = matrix( ce开发者_Python百科iling(10*runif(8)), nrow=4)
colnames(A) = c("country", "year_var")   
dfa = data.frame(A)                      

df1 = dfa[1,]                                                                
df2 = dfa[2,]                                                                
df3 = dfa[3,]                                                                
df4 = dfa[4,]                                                                
df_all = list(df1, df2, df3, df4)                                            
df_all  

Now I want to combine the list of interest by using variable a.

a <- "2,3,4"
b <- strsplit(a, ",")[[1]]

To combine this lists, I use the folling loop:

for (i in 1:length(b)){
c<-b[i]
aa <- df_all[c:c]
print(aa)
}

Now my question is, How can I combine this result and save this as as variable?

Thanks!


Would this work for you:

basnum<-as.integer(b)
do.call(rbind, df_all[basnum])

Through df_all[basnum], a list with only the relevant data.frames is created.

do.call takes a function and a list as parameters (and some more but not relevant right now). The items of the list are then passed on as parameters to the function.

So in this case, the above is the equivalent to calling:

rbind(df_all[[2]], df_all[[3]], df_all[[4]])

And this produces one data.frame holding all the rows of interest.

0

精彩评论

暂无评论...
验证码 换一张
取 消