by Guangming Lang
~1 min read


  • r

When doing data analysis in R, we often want to sort a vector or data frame. Sometimes, we want to undo the sorting. This usually happens inside of a function where you want to first sort the input object, do some operations and undo the sorting before you return the output object.

It’s fairly simple to unsort a vector in R. Here’s an example:

x = c("b", "c", "a")
ascend.order = order(x)

# sort x in ascending order
x = x[ascend.order]
## [1] "a" "b" "c"
# reverse the operation, unsort and get back x in original order 
x[ascend.order] = x
## [1] "b" "c" "a"