How do I sort one vector based on values of anothe

2019-01-03 08:38发布

I have a vector x, that I would like to sort based on the order of values in vector y. The two vectors are not of the same length.

x <- c(2, 2, 3, 4, 1, 4, 4, 3, 3)
y <- c(4, 2, 1, 3)

The expected result would be:

[1] 4 4 4 2 2 1 3 3 3

标签: sorting r
7条回答
Deceive 欺骗
2楼-- · 2019-01-03 08:48

[Edit: Clearly Ian has the right approach, but I will leave this in for posterity.]

You can do this without loops by indexing on your y vector. Add an incrementing numeric value to y and merge them:

y <- data.frame(index=1:length(y), x=y)
x <- data.frame(x=x)
x <- merge(x,y)
x <- x[order(x$index),"x"]
x
[1] 4 4 4 2 2 1 3 3 3
查看更多
冷血范
3楼-- · 2019-01-03 09:00

Here is a one liner...

y[sort(order(y)[x])]

[edit:] This breaks down as follows:

order(y)             #We want to sort by y, so order() gives us the sorting order
order(y)[x]          #looks up the sorting order for each x
sort(order(y)[x])    #sorts by that order
y[sort(order(y)[x])] #converts orders back to numbers from orders
查看更多
Deceive 欺骗
4楼-- · 2019-01-03 09:03

You could convert x into an ordered factor:

x.factor <- factor(x, levels = y, ordered=TRUE)
sort(x)
sort(x.factor)

Obviously, changing your numbers into factors can radically change the way code downstream reacts to x. But since you didn't give us any context about what happens next, I thought I would suggest this as an option.

查看更多
贼婆χ
5楼-- · 2019-01-03 09:05

what about this one

x[order(match(x,y))]
查看更多
我命由我不由天
6楼-- · 2019-01-03 09:07

How about?:

rep(y,table(x)[as.character(y)])

(Ian's is probably still better)

查看更多
等我变得足够好
7楼-- · 2019-01-03 09:10

In case you need to get order on "y" no matter if it's numbers or characters:

x[order(ordered(x, levels = y))]
4 4 4 2 2 1 3 3 3

By steps:

a <- ordered(x, levels = y) # Create ordered factor from "x" upon order in "y".
[1] 2 2 3 4 1 4 4 3 3
Levels: 4 < 2 < 1 < 3

b <- order(a) # Define "x" order that match to order in "y".
[1] 4 6 7 1 2 5 3 8 9

x[b] # Reorder "x" according to order in "y".
[1] 4 4 4 2 2 1 3 3 3
查看更多
登录 后发表回答