Simon
Simon

Reputation: 1111

Count within multiple nested lists R

Suppose I have a list of length 2, within which is another list of length 2, within which there is a data frame of numbers coded as either 0, 1 or 2 (bear with me!):

set.seed(42)
l1<-data.frame(sample(0:2, 5, replace = TRUE))
l2<-data.frame(sample(0:2, 5, replace = TRUE))
l<-list(l1,l2)
ll<-list(list(l,l), list(l,l))

I need to count the number of times either 1 or 2 appears within each data frame. I then need to sum these counts across all counts at the level above.

So for ll[[1]][[1]][[1]] the count would be 1, for ll[[1]][[1]][[2]] the count would be 4. Across those two dataframes the sum would be 5.

To give a more plain-English description of the real data I'm working with: the top level is the number of species (in this example, 2 species), the level below that is the year when data was recorded (in this example, data is collected in 2 different years). Below that is a location within which data are recorded. I need to know that, within years, how many times 1 or 2 appears across all locations (within that year).

There is perhaps a better way to describe this but so far it's eluding me. Any help would be appreciated.

Upvotes: 0

Views: 250

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

We can use purrr functions.

library(purrr)
map(ll, function(x) transpose(x) %>% map(~sum(unlist(.x) != 0)))

#[[1]]
#[[1]][[1]]
#[1] 2

#[[1]][[2]]
#[1] 8


#[[2]]
#[[2]][[1]]
#[1] 2

#[[2]][[2]]
#[1] 8

Upvotes: 1

lambruscoAcido
lambruscoAcido

Reputation: 572

A bit nested, but the solution should work:

lapply(ll, 
  function(l) 
    lapply(l, 
      function(li) sum(unlist(li) %in% 1:2)))

# [[1]]
# [[1]][[1]]
# [1] 5
#
# [[1]][[2]]
# [1] 5
# 
# 
# [[2]]
# [[2]][[1]]
# [1] 5
# 
# [[2]][[2]]
# [1] 5

Upvotes: 0

Related Questions