问题
I'm following up on this excellent answer. I have a function that subset
s what
(i.e., a variable) user requests out of this dataset.
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.
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?
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!
回答1:
We can modify the function to
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)
来源:https://stackoverflow.com/questions/58739159/conditionally-subset-an-additional-variable-and-append-it-to-the-previous-one-in