使用map2向tidymodels::workflow_set传递workflow_variables遇变量替换问题
解决tidymodels workflow_set变量组合传递问题
你遇到的问题核心是workflow_variables()采用**非标准求值(NSE)**机制,直接传入字符串参数时,它不会将字符串解析为变量名,而是把y和x当作字面量处理。要让它识别实际的变量名,需要将字符串转换为R的符号对象并注入函数中。
修改后的代码
library(tidymodels) library(rlang) combinations <- expand_grid( outc = c("measurement","Ln_measurement"), truth = c("callibrated_true","Ln_true","true_sqr","true_cub"), moisture = c("","Moisture_percent","Ln_Moisture","Moisture_sqr","Moisture_cub"), organic = c("","SOM_percent","Ln_SOM","SOM_sqr","SOM_cub") ) %>% tibble() %>% mutate( name = paste(outc, truth, moisture, organic, sep = "_"), # 过滤掉空字符串的无效预测变量 pred = pmap(list(truth, moisture, organic), ~ c(...) %>% discard(~ .x == "")), # 将字符串转为符号并注入workflow_variables variables = map2(outc, pred, function(y, x) { workflow_variables( outcomes = !!sym(y), predictors = !!!syms(x) ) }) )
关键修改说明
- 清理无效变量:原代码生成的
pred会包含空字符串(对应moisture或organic选空的情况),用discard(~ .x == "")去掉这些无效项,避免后续报错。 - 符号转换与注入:
- 用
sym(y)把单个结果变量的字符串转为R符号对象,再用!!注入到outcomes参数; - 用
syms(x)把预测变量的字符串向量转为符号列表,再用!!!注入到predictors参数。
- 用
验证效果
执行combinations$variables[[1]],会看到实际的变量名而非y和x:
combinations$variables[[1]] #> Outcomes: measurement #> Predictors: callibrated_true
内容的提问来源于stack exchange,提问作者Niall Marsay
相关产品推荐
相关产品推荐

