by Guangming Lang
~1 min read

Categories

  • 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]
print(x)
## [1] "a" "b" "c"
# reverse the operation, unsort and get back x in original order 
x[ascend.order] = x
print(x)
## [1] "b" "c" "a"