【问题标题】:Extracting conditional rows from a list of dataframes in a loop从循环中的数据框列表中提取条件行
【发布时间】:2021-06-23 22:33:00
【问题描述】:

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

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

ps.我怀疑,我应该在 ctlistG() 中使用 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 

【问题讨论】:

  • 如果您致电w7 %&gt;% filter(study.name == 'VanBe_Jng_KenA', !control),您将获得四行。然后你进一步过滤postoutcom。我建议先看这里。然后我建议你解释一下你实际上想要做什么,因为它根本不是很清楚。

标签: r function dataframe lapply mapply


【解决方案1】:

如果我们需要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]

【讨论】:

  • @rnorouzian 在这种情况下,您需要删除 lapply(m, 因为它不再是一个列表
  • Arun,您能否将其添加到您的答案中?请注意,“输入”也将是一个 data.frame。
  • @rnorouzian lapply 仅在“m”是数据集的list 时使用。如果是单人。要么你把它包装在 list and use the same command i..e. lapply(list(m), function(m1),...` 或 use m directly i.e. m[m$control == FALSE & ....`
  • @rnorouzian 我只是在开车。这个问题似乎得到了回答
  • @rnorouzian 我认为该帖子中的解决方案与我在这里提到的相同,即包装list
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2018-02-15
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
相关资源
最近更新 更多