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?
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.
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.
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.
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
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 NA
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With