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

如何在R语言中基于数据框内的公式引用计算结果?

在R中计算数据框每行的自定义公式

首先构造你的示例数据框:

df <- data.frame(
  Price = c(23, 25, 61),
  Quantity = c(1, 2, 1),
  Formula = c("Price*exp(Quantity)", "Price*log(Quantity)", "Price*Quantity+35"),
  stringsAsFactors = FALSE
)

注意:R中没有ln()函数,自然对数需要用log(),所以第二个公式要做上述修正,否则会报错。

方法一:基础R的apply函数

通过按行遍历数据框,将每行的变量赋值后解析执行公式:

df$Result <- apply(df, 1, function(row) {
  Price <- as.numeric(row["Price"])
  Quantity <- as.numeric(row["Quantity"])
  eval(parse(text = row["Formula"]))
})

方法二:tidyverse风格的rowwise

使用dplyr的行处理模式,逐行计算:

library(dplyr)

df <- df %>%
  rowwise() %>%
  mutate(Result = eval(parse(text = Formula))) %>%
  ungroup()

重要提醒

  • eval(parse())会执行字符串中的任意R代码,仅当公式来源完全可信时使用,避免注入恶意代码。
  • 确保公式中用到的函数在当前环境中存在,比如示例中的exp()、log()都是R基础函数,无需额外加载包。

执行后的数据框会新增Result列,存储每行公式的计算结果:

> df
  Price Quantity            Formula    Result
1    23        1 Price*exp(Quantity)  62.79065
2    25        2  Price*log(Quantity)  17.32868
3    61        1 Price*Quantity+35    96.00000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:55:23