Search code examples
rbar-chartlevels

Add value with no occurrences to table in R


Say I have a range of exam grades in a data frame column:

grades <- c("B", "C", "C", "C", "D", "D", "E", "F", "F")
grades.df <- data.frame(grades)

When illustrating this, the illustration would be a bit misleading, since it doesn't show 0 for a grade that everyone would expect to be there: "A":

barplot(table(grades))

How can I add "A" with 0 occurrences to this table, such that it would appear in the bar plot with zero height?


Solution

  • Use a factor with appropriate levels:

    grades <- factor(c("B", "C", "C", "C", "D", "D", "E", "F", "F"),levels=LETTERS[1:6])
    table(grades)
    grades
    A B C D E F 
    0 1 3 2 1 2 
    
    barplot(table(grades))
    

    Example Output showing bars for each factor level