Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort one vector based on other

Tags:

sorting

r

I have 2 vectors,

x <- c (1,4,6,7,9,2)
y <- c (2,6,5,1,8,9)

I want to sort x and y both. y is dependent on x. The result I want is

x = (1,2,4,6,7,9)
y = (2,9,6,5,1,8)

I know that I can get index of sorting x as

sort(x, index.return=TRUE)$ix

How do I sort vector y?

like image 513
Riddhi Avatar asked Apr 11 '17 08:04

Riddhi


People also ask

How do you sort a vector based on another?

If you cannot merge the data into a vector of pairs or struct with both, you could create a vector of iterators, or the indexes from 0 to size-1. Then sort this using a custom comparator. Finally, create a new vector, populating it using the iterators or indexes.

Can we sort vector of vector?

Ways to Sort a 2D Vector In sort(), it generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. This function is included in <algorithm> header file.

Can you sort a vector of pairs?

We can sort the vector of pairs using the generic sorting algorithm provided by STL. The std::sort function takes two iterators of the range to be sorted, and it rearranges the elements in non-descending order by default. In the case of pairs, the vector is sorted by the first element of each pair.


2 Answers

We can use that as index

i1 <- sort(x, index.return=TRUE)$ix

Or with order

i1 <- order(x)
x[i1]
#[1] 1 2 4 6 7 9

y[i1]
#[1] 2 9 6 5 1 8
like image 134
akrun Avatar answered Oct 05 '22 08:10

akrun


you are looking for order(). It generates an index based on the values in a vector. Using this index you can sort your y vector

y[order(x)]
# [1] 2 9 6 5 1 8

Be sure, however, that the vectors have the same length. Otherwise NAs will be generated

x <- c (1,4,6,7,9,2,3)
y <- c (2,6,5,1,8,9)
y[order(x)]
# [1]  2  9 NA  6  5  1  8

or some values will be lost

x <- c (1,4,6,7,9,2)
y <- c (2,6,5,1,8,9,3)
y[order(x)]
# [1] 2 9 6 5 1 8
like image 21
loki Avatar answered Oct 05 '22 10:10

loki