R中的列绑定 [英] Column binding in R

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

问题描述

我在R中使用cbind命令将许多data.frame绑定在一起,并且每个数据帧具有相同的列名,因此当我将它们全部绑定时,R会自动将列名从其原始名称更改.例如,有一个名为"X"的列,因此对于每个绑定,它都将其重命名为X.1,X.2,X.3等.有没有办法让我绑定它们而不更改任何列名,并且有多个具有相同名称的列?

I am using the cbind command in R to bind many data.frames together and each data frame has the same column names so when I bind them all, R automatically changes the column names from their original names. For example, there is a column named "X" so for each binding it renames this X.1, X.2, X.3 etc. Is there a way for me to bind them without changing any of the column names and have multiple columns with the same name?

我希望这样做的原因是,我可以按列名对合并后的data.frame进行排序,以将所有相等的命名列按合并后data.frame中的相同顺序放在一起.

The reason I wish to do this is so I can sort the combined data.frame after by the column names to get all the equal named columns together in the same order they were in the combined data.frame.

推荐答案

要说明我的评论中的要点:

To illustrate the points from my comment:

> d1 <- data.frame(a = 1:5,b = 1:5)
> d2 <- data.frame(a = letters[1:5],b = letters[1:5])
> cbind(d1,d2)
  a b a b
1 1 1 a a
2 2 2 b b
3 3 3 c c
4 4 4 d d
5 5 5 e e

> data.frame(cbind(d1,d2))
  a b a.1 b.1
1 1 1   a   a
2 2 2   b   b
3 3 3   c   c
4 4 4   d   d
5 5 5   e   e

> x <- data.frame(cbind(d1,d2))
> sort(colnames(x))
[1] "a"   "a.1" "b"   "b.1"
> x[,order(colnames(x))]
  a a.1 b b.1
1 1   a 1   a
2 2   b 2   b
3 3   c 3   c
4 4   d 4   d
5 5   e 5   e

这篇关于R中的列绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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