Count number of times each unique element appears in a list

Viewed 84

How do you count how many times each unique element appears in a list?

example_list <- list(
  c(1,1),
  c(1,2),
  c(1,1),
  c(1,2,3),
  c(1,1),
  c(1,2,3)
)

Edit: The unique elements are the vectors not the numbers inside the vectors

2 Answers

If it is the count of similar elements, one option is paste the elements in the list by looping over the list with sapply to create a vector, and get the frequency count with table

table(sapply(example_list, paste, collapse=' '))

#  1 1   1 2 1 2 3 
#    3     1     2 

Or another option is to convert to a wide dataset from the list and use count

library(dplyr)
library(tidyr)
tibble(col1 = example_list) %>% 
   unnest_wider(col1) %>% 
   count(across(everything()))

Elements at indices 1, 2, and 4 are unique and appear 3, 1, and 2 times respectively

table(match(example_list, example_list))

# 1 2 4 
# 3 1 2
Related