Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

sorting - R: Sort multiple columns by another data.frame?

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?

Here's some sample data.

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

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...