如果给出 NULL,我正在努力设置默认选择方法。例如,假设我想实现一个函数,对某个 tidyselect 方法、符号或字符串的所有值进行平方,如果没有给出,则默认情况下它对所有数值进行平方。这是我试图开始工作的案例的代表:
#Load package
suppressMessages(library(dplyr))
#Define function
square_columns <- function(data, target = NULL){
if (is.null(target)){
target <- rlang::expr(where(is.numeric))
}
data %>%
dplyr::mutate(
dplyr::across(!!target, magrittr::raise_to_power, 2)
)
}
# Examples
# Works
iris %>%
square_columns(target = 'Sepal.Length') %>%
invisible()
# Works
iris %>%
square_columns(target = c('Sepal.Length', 'Sepal.Width')) %>%
invisible()
# Works
iris %>%
square_columns() %>%
invisible()
# Fails
iris %>%
square_columns(target = contains('Sepal'))
#> Error: `contains()` must be used within a *selecting* function.
#> i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
# Fails
iris %>%
square_columns(target = Sepal.Length)
#> Error in square_columns(., target = Sepal.Length): object 'Sepal.Length' not found
由reprex 包于 2021-06-16 创建 (v2.0.0 )