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

如何在R中评估数据框存储函数的列并生成结果列?

解决方案

要实现根据my_function列的表达式计算生成outcome列,同时兼容列名带空格或纯数字的情况,可以用以下方法:

Base R 实现

# 定义表达式计算函数
calc_outcome <- function(expr_str, row_data) {
  # 遍历所有列名,将表达式中的变量替换为对应行的数值
  for (col in names(row_data)) {
    # 正则边界匹配确保完整替换变量名
    expr_str <- gsub(paste0("\\b", col, "\\b"), row_data[[col]], expr_str, fixed = FALSE)
  }
  # 解析并执行表达式
  eval(parse(text = expr_str))
}

# 逐行应用函数生成outcome列
my.df$outcome <- apply(my.df, 1, function(row) {
  calc_outcome(row["my_function"], row[-which(names(row) == "my_function")])
})

测试验证

测试第一个数据集

my.df <- data.frame(my_function=rep(c("Var1+Var 2","Var 2-Var1","(Var 2-(Var 2-Var1))/Var 2"), 1),
                    `Var1`=rep(1:1,3), 
                    `Var 2`=rep(5:5,3), check.names = FALSE)

# 运行计算代码后查看结果
my.df
#                  my_function Var1 Var 2 outcome
# 1                 Var1+Var 2    1     5     6.0
# 2                 Var 2-Var1    1     5     4.0
# 3 (Var 2-(Var 2-Var1))/Var 2    1     5     0.2

测试第二个数据集

my.df <- data.frame(my_function=rep(c("1000+2000","2000-1000","(2000-(2000-1000))/2000"), 1), `1000`=rep(1:1,3), `2000`=rep(5:5,3))

# 运行计算代码后查看结果
my.df
#                  my_function 1000 2000 outcome
# 1                 1000+2000    1    5     6.0
# 2                 2000-1000    1    5     4.0
# 3 (2000-(2000-1000))/2000    1    5     0.2

关键说明

  • 使用\\b正则边界匹配,避免变量名被部分替换(比如防止"Var1"被误替换到包含该字符串的其他内容中)
  • 通过apply逐行处理,确保每行的变量值与表达式正确对应
  • 支持带空格、纯数字的列名,row_data[[col]]可以正确提取任意格式列名的数值

内容的提问来源于stack exchange,提问作者J. Doe.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:50:28