[英]Subsetting each level of a vector with a function and returning a new dataframe (in R)
[英]Repeat a subsetting function by adding a new subsetting variable at each round in R
我有一個 function ( foo
) 來從列表L
中子集任何變量。 它完美無缺! 但是我可以默認將變量weeks
添加到任何被子集的變量嗎?
例如,假設我想對type == 1
進行子集化,我是否也可以默認將weeks
的所有唯一值(在我的數據中, weeks
有3
唯一值,不包括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.