I have a column of grades in a dataframe. I can generate a frequency table of these grades. However, I would like to change the order of the columns in the frequency table from A, A*, B, C, D, E, U to A*, A, B, C, D, E, U (an A* grade should appear first in list).
Not sure if this is possible. But it would be super helpful as I want to make a barplot of the data.
Thanks
Martyn
>Solution :
In this case, since table() is a named data structure you can simply specify the order using the desired order of names for indexing:
# Data
df <- data.frame(grade = rep(c("A", "A*", "B", "C", "D", "E", "U"), each = 10))
table(df$grade)[c("A*", "A", "B", "C", "D", "E", "U")]
# A* A B C D E U
# 10 10 10 10 10 10 10
So in a barplot:
ordr <- c("A*", "A", "B", "C", "D", "E", "U")
barplot(table(df$grade)[ordr])
For other cases using an unnamed vector, one would would need to use match:
grades <- c("A", "A*", "B", "C", "D", "E", "U")
ordr <- c("A*", "A", "B", "C", "D", "E", "U")
grades[match(grades, ordr)]
# [1] "A*" "A" "B" "C" "D" "E" "U"
