【发布时间】:2021-12-14 21:50:57
【问题描述】:
我正在尝试嵌套一个将两个字符串粘合在一起的函数,该函数使用组合字符串来命名数据框的列。但是,问题似乎是胶水表达式没有足够早地评估为字符串。我可以(并且应该)在将表达式作为参数传递给另一个函数之前强制对其进行评估吗?
library(tidyverse)
# define inner function
add_prefix <- function(string) {
x <- glue::glue("prefix_{string}")
return(as.character(x))
}
# define outer function
mod_mtcars <- function(df, name) {
df %>%
mutate({{ name }} := mpg ^ 2)
}
mod_mtcars(mtcars, add_prefix("foo"))
#> Error: The LHS of `:=` must be a string or a symbol
# alternative outer function with explicit enquoting
mod_mtcars2 <- function(df, name) {
name <- ensym(name)
df %>%
mutate(!!name := mpg ^ 2)
}
mod_mtcars2(mtcars, add_prefix("foo"))
#> Error: Only strings can be converted to symbols
由reprex package (v2.0.1) 于 2021-10-30 创建
【问题讨论】:
标签: r metaprogramming tidyeval