atreju
atreju

Reputation: 995

Reorder vector in R according to index vector

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.

Upvotes: 15

Views: 9394

Answers (1)

Artem
Artem

Reputation: 3414

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"

Upvotes: 5

Related Questions