基本上,我有一个初始 data.frame
我使用参与者姓名作为 row.names
.由于各种原因,我不得不堆叠然后合并长格式的数据,然后基于一个因子变量,我只选择了该数据的一部分。然后我汇总了这个,所以我再次拥有广泛的数据,参与者作为 row.names。但是,顺序不一样。所以如果我想 cbind
原始宽数据与新数据它会按照 row.names
的顺序弄乱我的数据是不同的。我试过 sort()
, order()
, transform()
并阅读了几个问题,但我找不到解决方法。
DF1
> V1 V2 V3
> AAA 24 22 37
> BBB 21 22 33
> CCC 30 32 38
> DDD 21 23 35
另一个数据帧具有相同的
dim()
,但是 row.names 的顺序不同。DF2 row.names
> BBB
> CCC
> AAA
> DDD
我要排序
DF1
基于 rownames(DF2)
以便变量与行名保持一致,然后我可以 cbind (D1, D2)
并且因为行名是相等的,所以相同的变量将属于同一个参与者。我可能把它复杂化了,抱歉:)基本上,我想重新排序整个
data.frame(DF1)
基于 DF2
中的行名.我知道这是一个蹩脚的问题,但我找不到有效的答案。
最佳答案
这是一种选择,使用内置 mtcars
用于说明的数据框:
# Create new sorted data frame. This is analogous to the second data frame
# by which you want to sort the first one.
mtcars.sorted = mtcars[order(rownames(mtcars)),]
# Sort original data frame by the order of the new data frame
mtcars[match(rownames(mtcars.sorted), rownames(mtcars)),]
因此,在您的情况下,代码将是:
DF1[match(rownames(DF2), rownames(DF1)), ]
关于r - 如何根据另一个数据框中的 row.names 对 data.frame 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36410485/