I have a function that subset
s what
(i.e., a variable) user requests out of this dataset.
The function works perfect. But I was wondering if there might be a way that in addition to what
user requests, the function always subset
entries that contain control == TRUE
and append those to what
the user has requested.
For example, suppose user wants to subset entries with type == 4
. In this dataset, there are 4 such entries. As reproducible code and data below show, this is done easily BUT there also are 4 other entries for which control == TRUE
, how can function find and append these 4 other entries to its currently-producible output?
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/izeh/i/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?
After Filter
ing the list
elements ('h1'), subset
those same elements from the original list
where the 'control' is TRUE (logical column) and theen rbind
the corresponding list
elements with Map
foo <- function(List, what){
s <- substitute(what)
h <- lapply(List, function(x) do.call("subset", list(x, s)))
h1 <- Filter(NROW, h)
h2 <- lapply(List[names(h1)], function(x) subset(x, control))
Map(rbind, h1, h2)
}
foo(L, type == 4)
#$Mubarak
# study.name group.name n d t.pair df mdif sdif mpre sdpre mpos sdpos r rev.sign autoreg post control outcome ESL prof
#43 Mubarak grA.short 17 NA 4.366 NA NA NA NA NA NA NA NA FALSE FALSE 1 FALSE 1 2 NA
#44 Mubarak grA.long 17 NA NA NA NA NA 0.395 0.280 0.520 0.205 0.6737 FALSE FALSE 2 FALSE 1 2 NA
#54 Mubarak grB.shortB 16 NA 7.864 NA NA NA NA NA NA NA NA TRUE FALSE 1 FALSE 2 2 NA
#55 Mubarak grB.longB 16 NA NA NA NA NA 0.105 0.030 0.056 0.025 0.5618 TRUE FALSE 2 FALSE 2 2 NA
#47 Mubarak Cont.short 13 NA 0.401 NA NA NA NA NA NA NA NA FALSE FALSE 1 TRUE 1 2 NA
#48 Mubarak Cont.long 13 NA NA NA NA NA 0.545 0.272 0.436 0.204 0.5320 FALSE FALSE 2 TRUE 1 2 NA
#49 Mubarak Cont.short 13 NA 0.401 NA NA NA NA NA NA NA NA FALSE FALSE 1 TRUE 1 2 NA
#50 Mubarak Cont.long 13 NA NA NA NA NA 0.545 0.272 0.436 0.204 0.5320 FALSE FALSE 2 TRUE 1 2 NA
#56 Mubarak Cont.shortB 13 NA 2.793 NA NA NA NA NA NA NA NA TRUE FALSE 1 TRUE 2 2 NA
#57 Mubarak Cont.longB 13 NA NA NA NA NA 0.093 0.032 0.078 0.032 0.9159 TRUE FALSE 2 TRUE 2 2 NA
# scope type
#43 2 4
#44 2 4
#54 2 4
#55 2 4
#47 2 2
#48 2 2
#49 2 2
#50 2 2
#56 2 2
#57 2 2