【问题标题】:Repeat a subsetting function by adding a new subsetting variable at each round in R通过在 R 中的每一轮添加一个新的子集变量来重复一个子集函数
【发布时间】: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


【解决方案1】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2018-10-12
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多