AlexLordThorsen
AlexLordThorsen

Reputation: 8488

R counting variable sized lists occurrences

I have a list of sorted sub lists of variable length. Each sub list is of variable size. I want to do two things. The first is sum the number of occurrences for each sub list. For example.

[[11533]]
[1] "Mexican"     "Restaurants"

[[11534]]
[1] "Mexican"     "Restaurants"

[[11535]]
[1] "Food"    "Grocery"    "dinner"

To

Count                 Item
2            "Mexican"     "Restaurants"

1           "Food"    "Grocery" "dinner"

And the second part is break each sub list into a vector and then sum each item. For example

[[11533]]
[1] "Mexican"     "Restaurants"

[[11534]]
[1] "Mexican"     "Restaurants"

[[11535]]
[1] "Food"     "Dinner"     "Grocery" 

To

"Mexican"
"Restaurants"
"Mexican"
"Restaurants" 
"Food"    
"Dinner"    
"Grocery" 

To

"Mexican" 2
"Restaurants" 2
"Food" 1    
"Dinner" 1    
"Grocery" 1

In python, I would use a for loop that looped through my primary list build a dictionary that be incremented by one every time I come across an item already in the dictionary. I'm a baby when it comes to R, however. Here's what I've tried so far.

tabled_data <- table(parsed_data)

tells me I need to have data that is of the same length

I also tried

for(i in length(parsed_data)){
  sum(parsed_data == parsed_data[i])
}

but I'm getting the error message "comparison of these types is not implemented"

Upvotes: 0

Views: 273

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 3380

You could use the table command:

testData <- list(c("Mexican","Restaurants"),c("Mexican","Restaurants"),c("Food","Grocery","dinner"))

# First question (join the vectors and then table them)
  table(sapply(testData,paste,collapse=""))

# Second problem (unlist the list and table it): 
  table(unlist(testData))

If the order within the vectors could change, you might want to sort them before pasting them.

Upvotes: 2

Related Questions