【发布时间】:2021-12-13 07:04:15
【问题描述】:
在下面我的玩具data 中,我重复group_by() 和filter() 变量:sample、group 和outcome(但不是time)。
我想知道是否有一种功能解决方案,我们可以在如下所示的foo() 函数内以循环方式提供我们想要group_by() 和filter() 的任意数量变量的名称?
library(tidyverse)
data <- expand_grid(study=1:3,sample=1:2,group=1:3,outcome=c("A","B"),time=0:2)
get_rows <- function(x) { # Helper function used in `filter()`
u <- unique(x)
n <- sample(c(if(is.character(x)) 0 else min(u)-1, u), 1)
if(n == n[1]) TRUE else x == n
}
DF <- data %>%
group_by(study) %>%
filter(get_rows(sample)) %>% # for sample
ungroup()
DF2 <- DF %>%
group_by(study) %>%
filter(get_rows(group)) %>% # for group
ungroup()
DF3 <- DF2 %>%
group_by(study) %>%
filter(get_rows(outcome)) %>% # for outcome
ungroup()
#============================================ HOW TO LOOP ABOVE IN `foo()` BELOW?
foo <- function(data, ..., exclude_vars = c("time")){
## SOLUTION
}
【问题讨论】:
标签: r dataframe function loops tidyverse