Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reorder frequency table in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])

enter image description here

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" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading