在R中:组合不同数据框的列 [英] in R: combine columns of different dataframes

查看:218
本文介绍了在R中:组合不同数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将三个不同数据框的每一列组合起来,以获得一个具有原始数据框长度和每个子对象三列的对象。每个原始数据帧都有10列和14行。
我尝试了一个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

但是最后我想要得到10个独立的三列数据框。
所以我想循环这个:

pre $ a $ cbind(imp.qua.00.09 [i] ,exp.qua.00.09 [i],net [i])

数据帧。但是如果我使用 t < - list(t,a),它会构造一个疯狂的列表。感谢。

解决方案

>是错的,你应该这样做:

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

您的代码错误因为在每个步骤中,您都将 t 转换为第一个元素是前一个 t (这是一个列表,除了第一次迭代),第二个元素是子集。所以基本上最后你得到了一个由两个元素组成的递归列表,其中第二个是data.frame子集,第一个是同样结构的两个元素的列表,共有十个级别。



无论如何,你的代码相当于这个单行(这可能更有效,因为它不执行任何列表连接):

  t < -  lapply(1:长度(净),
函数(i){cbind(imp.qua.00.09 [i],exp.qua。 00.09 [i],net [i])})


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.

解决方案

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

这篇关于在R中:组合不同数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆