Slowpoke Slowpoke - 1 month ago 14
R Question

R: undo ordering / unsort / switch back to initial order

Suppose I have a vector

test<-c("a","b","c","d","e")


I am changing the order using another vector of indexes (this is essential):

sortvect<-c(2,3,5,4,1)
test2<-test[sortvect]


After that I do some operations on
test2
and after that I want to switch back to initial order, having
sortvect
:

test<-give_my_order_back(test2,sortvect)


I have tried
test2[sortvect]
and
test2[rev(sortvect)]
but the solution is apparently different.

Answer

It is not that difficult. match(test, test2) will give you the index for reordering back.

test <- c("a","b","c","d","e")
sortvect <- c(2,3,5,4,1)
test2 <- test[sortvect]
sortback <- match(test, test2)
test2[sortback]
# [1] "a" "b" "c" "d" "e"
Comments