r语言 - 如何将负的tidyselect表达式的字符向量传递给select()



我想排除标题的列。我得到了一个exclude表达式:可能的列名和tidyselect表达式的混合。这是我尝试过的:

library(tidyverse)
library(rlang)
# my vector of columns and tidyselect expressions
exclude_expression <- c('-name', '-ends_with("_x")', '-id')
# dummy dataframe
# note: column "id" does not exist in the tibble
dat <- 
tribble(
~name,  ~coord_x, ~coord_y,
"ben",  "1",      "2",
"anna", "3",      "4"
)
# select statement where columns should be excluded, if they are present
dat %>% 
select(
!!!parse_exprs(exclude_expression)
)
#> Error: Can't subset columns that don't exist.
#> x Column `id` doesn't exist.

由reprex包(v2.0.0)创建于2022-06-03

重要的是,如果列不存在(与我的示例相反),管道不应该失败。我的示例的预期输出是:
# A tibble: 2 x 1
coord_y
<chr>  
1 2      
2 4

感觉问题比描述的更多,但本质上"如果列不存在,管道不应该失败"。您需要使用tidyselect helperany_of。几乎所有这些都将以字符向量作为输入。这些变量可以为每次迭代重新定义(根据注释)。

cols_that_exist <- c("name")
cols_might_exist <- c("id")
dat |>
select(
-contains(cols_that_exist), -ends_with('_x'), -any_of(cols_might_exist)
)

contains确实为部分匹配留下了空间。然后,您可以使用带有tidyval

的enquosure
dat |>
select(
-!!enquo(cols_that_exist), -ends_with('_x'), -any_of(cols_might_exist)
)

这应该使您的select语句"固定";但是允许您更新标准变量

最新更新