📜  r count dataframe (1)

📅  最后修改于: 2023-12-03 15:34:35.278000             🧑  作者: Mango

R Count Dataframe

count() function in R is used to count the number of occurrences of each unique value in a column or a combination of columns of a dataframe. It is an incredibly useful function for data analysis, as many statistical analyses require a count of observations.

Syntax
count(data, ..., name = "n")

where,

  • data: dataframe whose columns are to be counted
  • ...: columns to group by
  • name: name of the output column (defaults to "n")
Examples
# install and load required package
install.packages("dplyr")
library(dplyr)

# create a sample dataframe
df <- data.frame(
  name = c("John", "Jane", "Mary", "John"),
  age = c(24, 25, 23, 24),
  gender = c("M", "F", "F", "M"),
  stringsAsFactors = FALSE # to prevent automatic conversion to factors
)

# count the occurrences of each unique value in the 'name' column
count(df, name)

# count the occurrences of each unique combination of values in the 'name' and 'gender' columns
count(df, name, gender)

# use as a part of a pipe to count the occurrences of each unique value in multiple columns
df %>% 
  count(name, gender)

# rename the output column to 'count'
count(df, name, gender, name = "count")
Output

The output of count() function is a dataframe with the count of each unique value or combination of values. By default, the output column is named "n". However, it can be customized using the name parameter.