Reputation: 2244
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
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
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
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