Count the number of how often a number occurs across list elements

Viewed 59

Assume I have a list containing 5 vectors filled with integers between 1 and d, where d can be any integer

d = 30  #Intergers that I want to count, i.e. 1:30

set_list <- list(s1 = c(2,4,3,1,20,30), s2 = c(3,30,23,1,3,4), 
             s3=c(3,4,5,13,15,12, 23:29, 30), s4 = c(1:10, 13:15, 17),
             s5 = c(15:20, 23))

Without using a double loop over the list elements 1-5 and integers 1-30, I want to count how many each integer from 1 to d occurs in the list. E.g. 1 occurs 3 times, 2 occurs 2 times 3 occurs 3 times and so on. Note that I always want to check all intergers between 1 and d and not only the ones occurring in the list. So d can be much larger than the largest integer in set_list, e.g d=50. Hence, I can't use the table function. I figured out how to do it with 2 for loops but I think this is not an optimal solution.

2 Answers
table(ordered(unlist(set_list), levels = seq_len(d)))[seq_len(d)]

You could use vapply to do this (assuming you want a vector of integers):

vapply(seq_len(d), 
       function(x) {
         sum(x == unlist(set_list))
       }, 
       1L)

or purrr::map_int:

purrr::map_int(seq_len(d), ~sum(. == unlist(set_list)))
Related