Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder vector in R according to index vector

Tags:

sorting

r

I have a vector of elements that I want to bring in a new order. The order is defined in an index vector:

vector <- c("l","e","s","k","c","w","a","o","f","t","o","r","v")
index <- c(11,8,1,5,4,13,3,6,10,2,12,9,7)

I want to reorder the vector according to the index such that the first element goes to position 11, the second one position 8, the third to 1 etc.

I am sure that there is a very simple one-liner for this but I haven't found a solution yet despite playing around with sort() and order() for some time.

like image 202
atreju Avatar asked Jan 18 '26 17:01

atreju


1 Answers

Answer goes to akrun.

You can use a subsetting mechanism, which allows to manipulate indices inside of square brackets. order function returns the positions in the sorted vector. Then you use the output of order function to reorder a character string.

vector <- c("l", "e", "s", "k", "c", "w", "a", "o", "f", "t", "o", "r", "v")
index <- c(11, 8, 1, 5, 4, 13, 3, 6, 10, 2, 12, 9, 7)

vector[order(index)]
# [1] "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"
like image 60
Artem Avatar answered Jan 21 '26 06:01

Artem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!