rcategorical-datafrequency-table

How can I create a frequency table for a categorical variable?


I'm new to R and am working with a dataset that involves the favourite colours of people collected in a survey.

I simply have a list of responses with colours being repeated, and so I want to make a frequency table I can work from (to create stacked bar plots, or pie charts).

I tried just using the 'table' function but I was unable to use the created table any further when it came to making plots.

Here is an example of the data: mostFav

1      Blue
2       Red
3       Red
4     Black
5      Blue
6     Black
7    Purple
8      Blue
9    Orange
10    White
11    Green
12    Green
13     Blue
14     Blue
15     Blue
16     Blue
17    Brown
18     Blue
19     Blue
20    Black

Solution

  • I'm not sure I understand the problem; is this what you're trying to do?

    data <- structure(list(mostFav = c("Blue", "Red", "Red", "Black", "Blue", 
                                       "Black", "Purple", "Blue",
                                       "Orange", "White", "Green", "Green", 
                                       "Blue", "Blue", "Blue", "Blue",
                                       "Brown", "Blue", "Blue", "Black")),
                      class = "data.frame", row.names = c(NA, -20L))
    
    # Counts for each factor
    table(data)
    #> data
    #>  Black   Blue  Brown  Green Orange Purple    Red  White 
    #>      3      9      1      2      1      1      2      1
    
    barplot(table(data))
    

    # Frequency
    prop.table(table(data))
    #> data
    #>  Black   Blue  Brown  Green Orange Purple    Red  White 
    #>   0.15   0.45   0.05   0.10   0.05   0.05   0.10   0.05
    
    barplot(prop.table(table(data)))
    

    pie(prop.table(table(data)))
    

    Created on 2022-01-25 by the reprex package (v2.0.1)