You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在tidyverse自定义函数中传入数据框与列名完成mutate操作

错误原因

你传入的outcome是字符串类型的列名,原代码中as.numeric(outcome)是直接对"age"这个字符串本身做转换,没有把它映射为数据框内的对应列,所以每一行都返回了常量字符串的处理结果。

修正后的代码(tidyverse 推荐写法)

test_scale <- function(outcome, data){
  outcome_scaled = paste0(outcome, "_s")
  # 用.data代词+双层方括号提取字符串对应的列
  data = data %>% mutate(!!outcome_scaled := scale(as.numeric(.data[[outcome]])))
  # 用双层方括号取列避免返回tibble结构,直接输出数值向量
  print(head(data[[outcome_scaled]]))
}

调用test_scale("age", df)即可得到age列标准化后的预期结果。

可选的符号注入实现方式

你也可以先把字符串列名转为符号再解引用,效果完全一致:

test_scale <- function(outcome, data){
  outcome_sym <- rlang::sym(outcome)
  outcome_scaled = paste0(outcome, "_s")
  data = data %>% mutate(!!outcome_scaled := scale(as.numeric(!!outcome_sym)))
  print(head(data[[outcome_scaled]]))
}

内容的提问来源于stack exchange,提问作者Parseltongue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:36:10