有条件地子集一个附加变量

有条件地子集一个附加变量

本文介绍了有条件地子集一个附加变量,并将其附加到R中的前一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪这个 出色的答案 .我有subset s what(即变量)用户从 此数据集 .

I'm following up on this excellent answer. I have a function that subsets what (i.e., a variable) user requests out of this dataset.

我想知道如何在输出中添加control == TRUE条目如果它们不存在并将其附加到用户请求的what上,否则不做任何事情.

I was wondering how to add control == TRUE entries IF THEY ARE ABSENT in the output and append those to what the user has requested, otherwise don't do anything.

作为缺少control == T的示例,假设用户希望使用type == 4子集条目.在 此数据集 中这样的条目.如以下可重现的代码和数据所示,这很容易完成还有其他一些control == TRUE条目,如何通过功能找到并添加这些control == TRUE条目到当前可生产的输出?

As an example of control == T absent, suppose user wants to subset entries with type == 4. In this dataset, there are some such entries. As reproducible code and data below show, this is done easily BUT there also are some other entries for which control == TRUE, how can function find and append these control == TRUE entries to its currently-producible output?

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

As an example of control == T present, suppose user wants to subset entries with prof == 2. In this case control == T entries naturally come with the subset and don't need to be added. So don't do anything.

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!

推荐答案

我们可以将函数修改为

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)

这篇关于有条件地子集一个附加变量,并将其附加到R中的前一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:28