Reputation:
I have a function (foo
) to subset any variable from the list L
. It works perfect! But can I by default add variable weeks
to whatever variable being subsetted?
For example, suppose I want to subset type == 1
, can I also by default add all unique values of weeks
(in my data weeks
has 3
unique values excluding NA
) to that in a looped fashion:
type==1 & weeks==1
(Round 1) ; type==1 & weeks==2
(Round 2) ; type==1 & weeks==3
(Round 3)
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)
}
## EXAMPLE OF USE:
D <- read.csv("https://raw.githubusercontent.com/rnorouzian/m/master/k.csv", h = T) # DATA
L <- split(D, D$study.name) ; L[[1]] <- NULL # list `L`
## RUN:
foo(L, type == 1) # Requested
# Repeat Requested above in a loop:
foo(L, type==1 & weeks==1) # (Round 1)
foo(L, type==1 & weeks==2) # (Round 2)
foo(L, type==1 & weeks==3) # (Round 3)
Upvotes: 1
Views: 67
Reputation:
You could do:
foo <- function(List, what, time = 1){
s <- substitute(what)
s <- bquote(.(s) & weeks == time)
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)
}
# AND THEN:
lapply(1:3, function(i) foo(L, type == 1, time = i))
Upvotes: 1