简体   繁体   English

在R中:合并不同数据框的列

[英]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. 每个原始数据帧都有10列和14行。 I tried it with a for-loop, but the result is not usable for me. 我使用for循环进行了尝试,但结果对我而言不可用。

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. 但是最后,我想得到10个带有三列的分离数据帧。 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. 但是,如果我使用t <- list(t, a)它将构造一个疯狂的列表。 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的代码是错误的,您应该采用以下方式:

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. 您的代码是错误的,因为在每一步中,您都将t转换为一个列表,其中第一个元素是前一个t (即第一次迭代除外的列表),第二个元素是子集。 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. 因此,基本上,最终您得到了一种由两个元素组成的递归列表,其中第二个是data.frame子集,第一个又是具有相同结构的两个元素的列表,共十层。

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])})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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