从循环中的数据帧列表中提取条件行

Extracting conditional rows from a list of dataframes in a loop

在我下面的 split(w7, w7$study.name)[48] 调用中,有 4 行变量 control == FALSE.

但我想知道为什么 ctlistG(split(w7, w7$study.name)[48]) returns 只有一个这样的行?

ps. 我怀疑,我应该在 [=16= 中使用 mapply() 而不是 lapply() ].

可重现的 R 代码:

ctlist <- function(List, cont=FALSE, pos=1, outcom=1){

 if(!inherits(List, "list")) List <- list(List)  
  
h <- setNames(lapply(List, function(i) i[i$control==cont & i$post == pos & i$outcome == outcom, , drop = FALSE]), names(List)) 

Filter(NROW, h) }

#====================

ctlistG <- function(m){
  
  input <- setNames(lapply(m, function(i) rev(expand.grid(outcom = seq_len(max(i$outcome, na.rm = TRUE)), pos = seq_len(max(i$post, na.rm = TRUE))))), names(m))
  
  lapply(input, function(i) ctlist(m, cont = FALSE, pos = i$pos, outcom = i$outcom))   }

#==================== EXAMPLE OF USE:
w7 <- read.csv('https://raw.githubusercontent.com/rnorouzian/m/master/w7.csv')

ctlistG(split(w7, w7$study.name)[48])  # I expect 4 rows not 1 below!

#$VanBe_Jng_KenA
#$VanBe_Jng_KenA$VanBe_Jng_KenA
#        study.name YofPub group.name  n  d
#406 VanBe_Jng_KenA   2012         NA 34 NA 

如果我们需要 4 行,基于函数,我们可能需要 Map 而不是 lapply

out <- do.call(rbind, lapply(input, function(inp) 
      do.call(rbind, Map(function(p, o)
   do.call(rbind, lapply(m, function(m1)
    m1[m1$control == FALSE & m1$post == p & m1$outcome ==o, , drop = FALSE])),
      inp$pos, inp$outcom))))

数据

lst1 <- split(w7, w7$study.name)
m <- lst1[48]