本文介绍了R:按另一个data.frame对多列进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清如何根据另一列中的多列对一个data.frame进行排序.这个问题可以和向量一起使用 .有人可以建议一种与data.frames等效的方法吗?

I'm trying to make sense of how to sort one data.frame based on multiple columns in another. This question does this with vectors. Can someone suggest a way to do the equivalent with data.frames?

这是一些示例数据.

x1 <- data.frame(a=1:5, b=letters[1:5], c=rnorm(5))
x2 <- data.frame(a=c(4,4,2), b=c("d", "d", "b"), d=rnorm(3))

所以我想按x1的前两列对x2进行排序.我的实际数据要复杂得多,但这重复了这个想法...

So I want to sort x2 by the first two columns of x1. My actual data is much more complicated, but this replicates the idea...

推荐答案

这实际上取决于您的数据的真实外观.现在看来,您只需要对一列进行排序,就可以轻松地做到这一点:

It really depends on what your data really looks like. As it looks right now, you only need one column to sort, and that is easily done by:

x2[order(match(x2[,1],x1[,1])),]

如果您需要多个列,这将变得有些棘手.您必须指定要首先排序的那个,然后是第二个,例如:

If you need more than one column, this becomes a bit trickier. You will have to specify which one you want to sort first on, and which one second, eg :

x1 <- data.frame(a=rep(1:3,2), b=rep(letters[2:4],each=2), c=rnorm(6))
x2 <- data.frame(a=c(3,3,2), b=c("c", "d", "b"), d=rnorm(3))


x2[order(match(
  paste(x2[,1],x2[,2]),
  paste(x1[,1],x1[,2]))
),]

它首先在第一列上排序,然后在第二列上排序.您必须记住,x2中也需要x2中的所有组合. T

This sorts on the first column first, and then on the second. You have to keep in mind that you need all combinations in x2 also in x1. T

这篇关于R:按另一个data.frame对多列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:43