R: Count frequency of values in nested list with sub-elements
One way with lapply()
, unlist()
and table()
:
count <- table(unlist(lapply(lst, unique)))
count
# Austria Japan Sweden
# 5 1 2
as.data.frame(count)
# Var1 Freq
# 1 Austria 5
# 2 Japan 1
# 3 Sweden 2
Reproducible data (please provide yourself next time):
lst <- list(
c('Austria', 'Austria', 'Austria'),
c("Austria", "Sweden"),
c("Austria", "Austria", "Sweden", "Sweden", "Sweden", "Sweden"),
c("Austria", "Austria", "Austria"),
c("Austria", "Japan")
)
Here is another base R option
colSums(
do.call(
rbind,
lapply(
lst,
function(x) table(factor(x, levels = unique(unlist(lst)))) > 0
)
)
)
which gives
Austria Sweden Japan
5 2 1
An option is also to stack
into a two column data.frame, then take the unique
and apply the table
table(unique(stack(setNames(lst, seq_along(lst))))$values)
# Austria Japan Sweden
# 5 1 2