How to count unique values by group in the R programming language. More details: https://statisticsglobe.com/count-uni...
R code of this video:
data <- data.frame(x = c(1, 1, 2, 2, 2, 3, 3, 4, 5), # Create example data
group = c("A", "A", "A",
"B", "B",
"C", "C", "C", "C"))
data_count_1 <- aggregate(data = data, # Applying aggregate
x ~ group,
function(x) length(unique(x)))
install.packages("dplyr") # Install dplyr package
library("dplyr") # Load dplyr
data_count_2 <- data %>% # Applying group_by & summarise
group_by(group) %>%
summarise(count = n_distinct(x))
install.packages("data.table") # Install & load data.table
library("data.table")
data_table <- data.table(data) # Applying data.table, length & unique
data_count_3 <- data_table[ , .(count = length(unique(x))), by = group]
Follow me on Social Media:
Facebook: / statisticsglobecom
LinkedIn: / statisticsglobe
Patreon: / statisticsglobe
Pinterest: https://www.pinterest.de/JoachimSchork
Reddit: / joachimschork
Twitter: / joachimschork