Repeat a subsetting function by adding a new subsetting variable at each round in R

丶灬走出姿态 提交于 2019-12-04 02:00:32

问题


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)

回答1:


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))


来源:https://stackoverflow.com/questions/58454100/repeat-a-subsetting-function-by-adding-a-new-subsetting-variable-at-each-round-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!