本文介绍了通过在R的每个回合中添加新的子集变量来重复子集函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数(foo)可以对列表L中的任何变量进行子集化.完美的作品!但是我可以默认将变量weeks添加到子集的变量中吗?

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?

例如,假设我想对type == 1进行子集设置,我是否还可以默认将weeks的所有唯一值(在我的数据weeks具有3唯一值,但不包括NA)添加到循环时尚:

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(第1回合); type==1 & weeks==2(第二回合); type==1 & weeks==3(第三回合)

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)

推荐答案

您可以这样做:

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

这篇关于通过在R的每个回合中添加新的子集变量来重复子集函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:03