我需要在多个表达式上动态选择变量。考虑以下示例:
library(tidyverse)
set.seed(42)
df <- tibble(
grey_dog = runif(n = 69),
white_bear = runif(n = 69),
blue_oyster = runif(n = 69),
white_lobster = runif(n = 69),
green_dog = runif(n = 69)
)
df %>%
dplyr::select(
(contains("dog") & contains("green")) |
(contains("white") & contains("bear"))
)
我没有明确选择,而是有包含我想要选择的信息的向量:
x <- c(green = "dog", white = "bear")
所以我希望连接一个可以用作整洁选择的字符串:
s <- paste0("(", paste0("contains(", names(x),") & contains(", x, ")"), ")", collapse = " | ")
dplyr::select(df, s)
这失败了:
Error: Can't subset columns that don't exist.
x Column `(contains(green) & contains(dog)) | (contains(white) & contains(bear))` doesn't exist.
Run `rlang::last_error()` to see where the error occurred.
关于如何做到这一点的任何想法?