The “count” Function in R

  • Package: dplyr

  • Purpose: To count the frequency of each unique value in a variable.

  • General Class: Data Manipulation

  • Required Argument(s):

    • data: The data frame containing the variable to count.

  • Notable Optional Arguments:

    • ...: Columns to group by for counting.

  • Example (with Explanation):

  • # Load necessary packages
    library(dplyr)

    # Create a sample data frame
    data <- data.frame(
    ID = c(1, 2, 3, 4, 5),
    category = c("A", "B", "A", "C", "B")
    )

    # Count the frequency of each category
    result <- data %>%
    count(category)

    # Display the result
    print(result)

  • In this example, the count function from the dplyr package is used to count the frequency of each unique category in the ‘category’ column of the sample data frame data. The result is a new data frame result with two columns: ‘category’, containing the unique categories, and ‘n’, containing the frequency of each category.

Previous
Previous

The “top_n” Function in R

Next
Next

The “case_when” Function in R