您正沉浸在整洁评估的美妙世界中,您必须ensym 或enquo 列的名称:
my_function <- function(table_name, col_name) {
.col = ensym(col_name)
table_name %>%
mutate(!!paste0("new_", col_name) := case_when(as.numeric(!!.col) <=4 ~ -1,
as.numeric(!!.col) > 4 & as.numeric(!!.col) <= 8 ~ 0,
as.numeric(!!.col) > 8 ~ 1))
}
df = tibble(x=1:10)
my_function(df, "x")
# A tibble: 10 x 2
x new_x
<int> <dbl>
1 1 -1
2 2 -1
3 3 -1
4 4 -1
5 5 0
6 6 0
7 7 0
8 8 0
9 9 1
10 10 1
您可以在Programming with dplyr 小插图上了解更多信息(包括运算符!! 和:=)。
我的示例使用 ensym 并将参数作为字符串,以坚持您的函数。但是,更常见的是使用 enquo 并将参数作为列名:
my_function2 <- function(table_name, col_name) {
.col = enquo(col_name)
table_name %>%
mutate(!!paste0("new_", quo_name(.col)) := case_when(as.numeric(!!.col) <=4 ~ -1,
as.numeric(!!.col) > 4 & as.numeric(!!.col) <= 8 ~ 0,
as.numeric(!!.col) > 8 ~ 1))
}
my_function2(df, x) #no quotes on the x!
# A tibble: 10 x 2
x new_x
<int> <dbl>
1 1 -1
2 2 -1
3 3 -1
4 4 -1
5 5 0
6 6 0
7 7 0
8 8 0
9 9 1
10 10 1
不过,您不应该构建一个接受数字并在 mutate 中使用它的函数吗?这是dplyr v1.0.0 的示例:
my_function3 = function(x){
case_when(as.numeric(x) <=4 ~ -1,
as.numeric(x) > 4 & as.numeric(x) <= 8 ~ 0,
as.numeric(x) > 8 ~ 1)
}
df %>% mutate(across(x, my_function3, .names="new_{col}"))