stringr::str_glue()与purrr::map()配合时无法识别函数参数的问题
问题原因
stringr::str_glue 默认会在全局环境中查找模板里的变量,而非调用它的函数的局部环境。当你在 fn_render_ce_template 内部用 purrr::map_chr 调用 str_glue 时,str_glue 无法找到函数局部定义的 file_name,因此抛出"object 'file_name' not found"错误;如果全局环境中存在 file_name,它就会直接使用全局变量,所以能正常运行。
解决方法
以下是几种可行的修复方案:
1. 指定 str_glue 的查找环境
利用 str_glue 的 .str_env 参数,明确告诉它在当前函数的局部环境中查找变量:
library(purrr) library(stringr) fn_render_ce_template <- function(file_name, templates) { map_chr(templates, ~ str_glue(.x, .str_env = environment())) }
如果使用 rlang 包,也可以用 current_env() 替代 environment(),效果一致:
library(rlang) fn_render_ce_template <- function(file_name, templates) { map_chr(templates, ~ str_glue(.x, .str_env = current_env())) }
2. 显式传递变量给 str_glue
在匿名函数中把 file_name 作为参数直接传给 str_glue,避免环境查找问题:
fn_render_ce_template <- function(file_name, templates) { map_chr(templates, function(tmpl) { str_glue(tmpl, file_name = file_name) }) }
3. 使用 map2 绑定变量与模板
如果 file_name 是单个值,用 map2_chr 将模板向量和 file_name 配对迭代,确保变量能被 str_glue 访问:
fn_render_ce_template <- function(file_name, templates) { map2_chr(templates, file_name, ~ str_glue(.x, file_name = .y)) }
内容的提问来源于stack exchange,提问作者joshbrows
相关产品推荐
相关产品推荐

