【发布时间】:2020-02-15 15:25:18
【问题描述】:
我有一个函数 (foo) 可以对列表 L 中的任何变量进行子集化。它完美无缺!但是我可以默认将变量 weeks 添加到任何被子集的变量吗?
例如,假设我想对type == 1 进行子集化,我是否也可以默认将weeks 的所有唯一值(在我的数据中weeks 具有3 唯一值,不包括NA)添加到循环时尚:
type==1 & weeks==1(第一轮) ; type==1 & weeks==2(第二轮); type==1 & weeks==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)
【问题讨论】:
-
看起来你自己回答了。太好了!
标签: r function loops dataframe subset