简体   繁体   English

在多个嵌套列表中计数 R

[英]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!):假设我有一个长度为 2 的列表,其中是另一个长度为 2 的列表,其中有一个编码为 0、1 或 2 的数字数据框(请耐心等待!):

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.我需要计算每个数据框中出现 1 或 2 的次数。 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.所以对于ll[[1]][[1]][[1]]计数为 1,对于ll[[1]][[1]][[2]]计数为 4。在这两个中数据帧总和为 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).为了对我正在处理的真实数据提供更简单的英语描述:顶层是物种数量(在本例中为 2 个物种),下面的级别是记录数据的年份(在本例中,数据是在 2 年不同的年份收集的)。 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).我需要知道,在几年内,有多少次 1 或 2 出现在所有位置(在那一年内)。

There is perhaps a better way to describe this but so far it's eluding me.也许有更好的方法来描述这一点,但到目前为止我还没有想到。 Any help would be appreciated.任何帮助,将不胜感激。

We can use purrr functions.我们可以使用purrr函数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM