【问题标题】:conditionally subset an additional variable and append it to the previous one in R有条件地对附加变量进行子集化并将其附加到 R 中的前一个变量
【发布时间】:2020-03-03 11:15:19
【问题描述】:

我正在跟进这个 excellent answer。我有一个函数,subsets what(即变量)用户从this dataset 请求。

我想知道如何在输出中添加control == TRUE 条目IF THEY ARE ABSENT 并将它们附加到用户请求的what,否则不要执行任何操作。

作为control == T 不存在的示例,假设用户希望使用type == 4 对条目进行子集化。在this dataset 中有一些这样的条目。正如下面的可重现代码和数据所示,这很容易完成但是还有一些其他条目需要control == TRUE,函数如何找到并附加这些control == TRUE 条目到它的当前可生产输出?

作为control == T 的示例,假设用户希望使用prof == 2 对条目进行子集化。在这种情况下,control == T 条目自然随子集一起提供,不需要添加。所以什么都别做。

foo <- function(List, what){       ## The subsetting function

  s <- substitute(what) 

  h <- lapply(List, function(x) do.call("subset", list(x, s)))

  Filter(NROW, h)
}


D <- read.csv("https://raw.githubusercontent.com/rnorouzian/m/master/k.csv", h = T) ## Dataset
L <- split(D, D$study.name) ; L[[1]] <- NULL   ## list by `study.name`

foo(L, type == 4)    ## subsets entries with `type == 4`. BUT how can function `foo` 
                     ## find and append entries with `control == TRUE` to its output?

foo(L, prof == 2)   # entries with `control == TRUE` are already present don't do anything!

【问题讨论】:

    标签: r list function dataframe subset


    【解决方案1】:

    我们可以修改函数为

    foo <- function(List, what){       ## The subsetting function
    
      s <- substitute(what) 
    
      h <- lapply(List, function(x) do.call("subset", list(x, s)))
    
      h1 <- Filter(NROW, h)
      nm1 <- names(which(!sapply(h1, function(x) any(x$control))))
      if(length(nm1) > 0) {
      h1[nm1]  <- Map(function(x, y) rbind(y, x[x$control, ]), List[nm1], h1[nm1])
      }
      h1
    
    }
    
    foo(L, type == 4) 
    foo(L, prof == 2)
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2017-11-28
      • 2021-02-19
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      相关资源
      最近更新 更多