📅  最后修改于: 2023-12-03 15:34:35.278000             🧑  作者: Mango
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.
count(data, ..., name = "n")
where,
data
: dataframe whose columns are to be counted...
: columns to group byname
: name of the output column (defaults to "n")# 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")
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.