Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sorting

r

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.

like image 437
Slowpoke Avatar asked Oct 05 '16 21:10

Slowpoke


2 Answers

Alternatively order can also do this quite simply

test2[order(sortvect)]
# [1] "a" "b" "c" "d" "e"
like image 115
dww Avatar answered Oct 31 '22 01:10

dww


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"
like image 31
Zheyuan Li Avatar answered Oct 31 '22 02:10

Zheyuan Li