The count Function in R


In R, count() lets you quickly count the unique values of one or more variables: df %>% count(a, b) is roughly equivalent to df %>% group_by(a, b) %>% summarise(n = n()).

Here is some online documentation here.

We can manually create a data frame and practice out count() function on that. Here is a script you could run in RStudio.

id <- c(1:3)
name <- c("Susan Smith", "Rachel Hickman", "Bob Johnson")
job_title <- c("Clerical", "President", "Management")
month_start <- c("Dec", "Jan", "Apr")
month_levels <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
month_begin <- factor(month_start, levels = month_levels)
month_begin <- month_start
employee <- data.frame(id, name, job_title, month_begin)
employee
employee %>% count(month_begin)

Below is part of the output from the console. Of course we only have a small amount of data to work with here.

> employee %>% count(month_begin)
  month_begin n
1         Apr 1
2         Dec 1
3         Jan 1

Leave a comment

Your email address will not be published. Required fields are marked *