R - change levels of a factor with reorder()

21 Jan 2018

Reorder level of a vector using reorder(x, X, FUN):

returns a factor or an ordered factor (depending on the value of order), with the order of the levels determined by FUN applied to X grouped by x.

x <- data.frame(condition=c("A", "A", "A", "B", "B"), count = c(10,10,15,1,1))
# x
#   condition count
# 1         A    10
# 2         A    10
# 3         A    15
# 4         B     1
# 5         B     1
levels(x$condition)
# [1] "A" "B"
x$condition <- reorder(x$condition, x$count, mean)
levels(x$condition)
# [1] "B" "A"

[ R  function  factor  ]