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

Alternatively order can also do this quite simply

test2[order(sortvect)]
# [1] "a" "b" "c" "d" "e"

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"

As pointed out by dww, to reverse the ordering, just use order on the index you used for deordering:

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

this allows you to go back to original order even if you modified the object in between:

test <- c("a","b","c","d","e")
sortvect <- c(2,3,5,4,1)
test2 <- test[sortvect]
set.seed(12)
test2 <- paste0(sample(c("a","b","c","d","e"), 5, replace = F),test2)
test2[order(sortvect)]
[1] "ba" "ab" "dc" "ed" "ce"

Tags:

Sorting

R