Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the frequency of items in a list with the different length

Tags:

list

r

Suppose I have the following list:

test<-list(c("a","b","c"),c("a"),c("c"))
>test
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "a"

[[3]]
[1] "c"

What do I do(or functions to use) to get the frequency of unique items in a list like this:?

a 2
b 1
c 2

I tried using table(test), but I get the following error

> table(test)
Error in table(test) : all arguments must have the same length
like image 647
Alby Avatar asked Dec 16 '22 13:12

Alby


1 Answers

test <- list(c("a", "b", "c"), c("a"), c("c"))
# If you want count accross all elements
table(unlist(test))
## 
## a b c 
## 2 1 2 


# If you want seperate counts in each item of list
lapply(test, table)
## [[1]]
## 
## a b c 
## 1 1 1 
## 
## [[2]]
## 
## a 
## 1 
## 
## [[3]]
## 
## c 
## 1 
## 
like image 172
CHP Avatar answered Jan 31 '23 01:01

CHP