使用tidyeval编写自定义case_when函数以在dplyr mutate中使用 [英] Writing a custom case_when function to use in dplyr mutate using tidyeval
问题描述
我正在尝试编写自定义case_when函数以在dplyr中使用.我一直在阅读其他问题中张贴的tidyeval示例,但仍然不知道如何使其工作.这里是一个代表:
I'm trying to write a custom case_when function to use inside dplyr. I've been reading through the tidyeval examples posted in other questions, but still can't figure out how to make it work. Here's a reprex:
df1 <- data.frame(animal_1 = c("Horse", "Pig", "Chicken", "Cow", "Sheep"),
animal_2 = c(NA, NA, "Horse", "Sheep", "Chicken"))
translate_title <- function(data, input_col, output_col) {
mutate(data,
!!output_col := case_when(
input_col == "Horse" ~ "Cheval",
input_col == "Pig" ~ "Рorc",
input_col == "Chicken" ~ "Poulet",
TRUE ~ NA)
)
}
df1 %>%
translate_title("animal_1", "animaux_1") %>%
translate_title("animal_2", "animaux_2")
当我尝试运行此命令时, mutate_impl(.data,点)中的错误:评估错误:必须为字符串类型,而不是逻辑类型.
When I try to run this, I'm getting
Error in mutate_impl(.data, dots) : Evaluation error: must be type string, not logical.
我实际上还想重写该函数,以便可以像这样使用它:
Also I would actually like to rewrite the function so that it can be used like this:
df1 %>%
mutate(animaux_1 = translate_title(animal_1),
animaux_2 = translate_title(animal_2)
)
但不确定如何.
推荐答案
根据您想如何将输入传递给函数,可以通过两种方式解决它:
Depending on how you want to pass your input to the function you can solve it in two ways :
1)使用 {{}}
library(dplyr)
translate_title <- function(data, input_col, output_col) {
mutate(data,
!!output_col := case_when(
{{input_col}} == "Horse" ~ "Cheval",
{{input_col}} == "Pig" ~ "Рorc",
{{input_col}} == "Chicken" ~ "Poulet",
TRUE ~ NA_character_)
)
}
df1 %>%
translate_title(animal_1, "animaux_1") %>%
translate_title(animal_2, "animaux_2")
# animal_1 animal_2 animaux_1 animaux_2
#1 Horse <NA> Cheval <NA>
#2 Pig <NA> Рorc <NA>
#3 Chicken Horse Poulet Cheval
#4 Cow Sheep <NA> <NA>
#5 Sheep Chicken <NA> Poulet
2)传递使用 sym
和 !!
translate_title <- function(data, input_col, output_col) {
mutate(data,
!!output_col := case_when(
!!sym(input_col) == "Horse" ~ "Cheval",
!!sym(input_col) == "Pig" ~ "Рorc",
!!sym(input_col) == "Chicken" ~ "Poulet",
TRUE ~ NA_character_)
)
}
df1 %>%
translate_title("animal_1", "animaux_1") %>%
translate_title("animal_2", "animaux_2")
这篇关于使用tidyeval编写自定义case_when函数以在dplyr mutate中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!