简体   繁体   中英

in R: combine columns of different dataframes

I try to combine each columns of three different dataframes to get an object with the same length of the original dataframe and three columns of every subobject. Each of the original dataframe has 10 columns and 14 rows. I tried it with a for-loop, but the result is not usable for me.

t <- NULL
for(i in 1 : length(net)) { 
    a <- cbind(imp.qua.00.09[i], exp.qua.00.09[i], net[i])
    t <- list(t, a) 
}
t

But in the end I would like to get 10 seperated dataframes with three columns. So I want to loop through this:

a <- cbind(imp.qua.00.09[i], exp.qua.00.09[i], net[i])

for every column of each original dataframe. But if I use t <- list(t, a) it constructs a crazy list. Thanks.

这应该工作:

do.call(cbind,list(imp.qua.00.09, exp.qua.00.09, net))

The code you're using to append elements to t is wrong, you should do in this way:

t <- list()
for(i in 1:length(net)) { 
  a <- cbind(imp.qua.00.09[i], exp.qua.00.09[i], net[i])
  t[[length(t)+1]] <- a
}
t

Your code is wrong since at each step, you transform t into a list where the first element is the previous t (that is a list, except for the first iteration), and the second element is the subset. So basically in the end you're getting a sort of recursive list composed by two elements where the second one is the data.frame subset and the first is again a list of two elements with the same structure, for ten levels.

Anyway, your code is equivalent to this one-liner (that is probably more efficient since it does not perform any list concatenation):

t <- lapply(1:length(net),
            function(i){cbind(imp.qua.00.09[i], exp.qua.00.09[i], net[i])})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM