Supposing I have (very simple example):
df <- data.frame(factor_name = c("fac_Y", "fac_Y", "fac_Y", "fac_X", "fac_X", "fac_X", "fac_X", "fac_X", "fac_X"), factor_level = c("cherry", "apple", "peach", 2, 1, 3, 4, 6, 8), value = c(1, 3, 2, 6, 3, 4, 1, 5, 2)) I need to sort df based on factor_name and factor_level without relying on alphabetic/numerical order (because in the more complex case I'm working on, the sort order is completely unrelated to these things) such that:
(i) factor_name should be sorted as (fac_X, fac_Y)
(ii) within fac_X, the factor_level sort order should be (1, 2, 3, 4, 6, 8)
(iii) within fac_Y, the factor_level sort order should be ("apple", "peach", "cherry")
So I'll need to supply information by hand about the ordering I want (ie (i)-(iii) above) but I'm unsure how to do that.
I'd like my output therefore to be:
df_sorted <- data.frame(factor_name = c("fac_X", "fac_X", "fac_X", "fac_X", "fac_X", "fac_X", "fac_Y", "fac_Y", "fac_Y"), factor_level = c(1, 2, 3, 4, 6, 8, "apple", "peach", "cherry"), value = c(3, 6, 4, 1, 5, 2, 3, 2, 1)) Can anyone help please? Thank you.
df[order(df$factor_name,df$factor_level,df$value),]