首先为这个有点缺乏信息的标题道歉
我有一个闪亮的应用程序,用户下载许多可能的数据集之一,并且对于某些列可以执行过滤器以生成 data.frame 输出
无论下载的数据集如何,我都想标准化代码
问题是列名因数据集而异,并且我希望过滤的列数不定
就创建输入而言,我已经使用 tidyeval 方法调整了这个解决方案。但是,我在输出时遇到了困难,而不必根据可以过滤的列数诉诸大量 if else 语句
这是一个基于数据集的(非闪亮)示例,其中我有 2 个可过滤列,一个始终需要的值列和最终输出中不需要的一列
library(tidyverse)
## desired columns
my_cols <- c("col 1", "another col")
# selected input
input_1 <- c("A","B")
input_2 <- c("Z")
l <- list(`col 1` = rep(c("A","B","C"),times=3), `another col` =
rep(c("X","Y","Z"),each=3), Value = c(1:9),`Unwanted 1`=(9:1))
df <- as_tibble(l)
# this creates the right number of correctly-named columns
for (i in seq_along(my_cols)) {
assign(paste0("col_", i), sym(my_cols[i]))
}
## This produces output but wish to adapt
## to varying number of columns
df %>%
filter(!!col_1 %in% input_1) %>%
filter(!!col_2 %in% input_2) %>%
select(!!col_1, !!col_2, Value)
# `col 1` `another col` Value
# <chr> <chr> <int>
# 1 A Z 7
# 2 B Z 8
所以这是我希望适应的最后一段代码,以考虑 my_cols 的可变长度
TIA