我在根据变量选择负列时遇到问题。我在这里发现了一个类似的问题:
https ://github.com/tidyverse/dplyr/issues/4813但提供的解决方案不起作用(见repex
下文)。如果有人知道解决方法,那将不胜感激!这是一个repex
问题:
# Load package
library(dplyr, warn.conflicts = F)
ex_data <- tibble(a = 1, b = 2)
# example functions
## Function for checking if target was provided
## else defaults to all numeric columns
check_target <- function(target) {
target
target_quoted <- rlang::enquo(target)
if (rlang::quo_is_null(target_quoted)) {
rlang::expr(where(is.numeric))
} else{
rlang::expr(!!target)
}
}
## Just soft wrappers to show how the preivews
## function could be used
my_select_embrace <- function(data, target = NULL){
target <- check_target(target)
data %>%
select({{ target }})
}
my_select_bang <- function(data, target = NULL){
target <- check_target(target)
data %>%
select(!!target)
}
# Works
ex_data %>%
select(-1) %>%
invisible()
ex_data %>%
my_select_bang(tidyselect::vars_select_helpers$where(is.numeric)) %>%
invisible()
ex_data %>%
my_select_bang() %>%
invisible()
# Fails
ex_data %>%
my_select_embrace() %>%
invisible()
#> Error: object 'is.numeric' not found
ex_data %>%
my_select_bang(tidyselect::vars_select_helpers$contains('a')) %>%
invisible()
#> Error: `contains()` must be used within a *selecting* function.
#> i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
ex_data %>%
my_select_embrace(tidyselect::vars_select_helpers$where(is.numeric)) %>%
invisible()
minus_one <- -1
ex_data %>%
my_select_embrace(minus_one)
#> Error: Selections can't have negative values.
ex_data %>%
my_select_bang(minus_one)
#> Error: Selections can't have negative values.
由reprex 包于 2021-06-21 创建 (v2.0.0 )