簡體   English   中英

通過在 R 中的每一輪添加一個新的子集變量來重復子集 function

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

我有一個 function ( foo ) 來從列表L中子集任何變量。 它完美無缺! 但是我可以默認將變量weeks添加到任何被子集的變量嗎?

例如,假設我想對type == 1進行子集化,我是否也可以默認將weeks的所有唯一值(在我的數據中, weeks3唯一值,不包括NA )以循環方式添加到其中:

type==1 & weeks==1 (第一輪); type==1 & weeks==2 (第 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)

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM