alyssaeliyah
alyssaeliyah

Reputation: 2244

Group the same list elements and count its occurences in R

I have a list element, say for example:

l = list("Android", "iPhone", "Android", "iPhone", "iPhone")

I want to have 2 vectors that contains the unique list elements and the count of occurrences of the list element.

a = c("Android", "iPhone")
b = c(2, 3)

How will I do that easily in R? In my situation, I have a big data that's why I'm finding a quick solution to solve this problem. Any help will be very much appreciated.

Upvotes: 2

Views: 1046

Answers (3)

Roman Luštrik
Roman Luštrik

Reputation: 70653

Or you can unlist and calculate frequencies. Result is a table, where you can access names and values

x <- table(unlist(l))

names(x)
[1] "Android" "iPhone" 

str(x)
 'table' int [1:2(1d)] 2 3
 - attr(*, "dimnames")=List of 1
  ..$ : chr [1:2] "Android" "iPhone"

Upvotes: 2

MKR
MKR

Reputation: 20095

In that way an easy way could be to use unlist function and then applytable to get the frequency for each word/name:

table(unlist(l))
#Android  iPhone 
#      2       3 

Upvotes: 0

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

Maybe this? It converts the list to a vector, then make a table, and finally make the table a data.frame.

dat <- data.frame(table(sapply(l, function(x) x)))
dat
#     Var1 Freq
#1 Android    2
#2  iPhone    3

You can access the individual columns if you wish.

Upvotes: 1

Related Questions