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

如何使用dplyr基于变量存储的公式生成cutoff新列?

嘿,我来帮你解决这个问题!

问题出在哪?

你现在的代码里,a2是个字符串("mean * .290"),直接在mutate()里写cutoff=a2的话,只是把这个字符串原封不动塞到每一行里,根本没执行这个公式计算数值——这就是结果不符合预期的核心原因。

两种可行的解决方案

我们需要把字符串形式的公式转换成能被R执行的表达式,再让dplyr帮我们计算每一行的结果:

方案1:用eval(parse())快速解决

parse()能把字符串转成表达式,eval()负责执行它,组合起来就能得到计算结果:

library(dplyr)

a1 <- "AVG(C1) * .290"
a2 <- gsub("AVG[(]C1[)]","mean",a1)

newiris <- iris %>% 
  group_by(Species) %>% 
  summarize(n = n(),
            mean = mean(Petal.Width), 
            cv = sd(Petal.Width)/mean(Petal.Width)*100) %>% 
  mutate(cutoff = eval(parse(text = a2)))

# 查看结果
newiris

方案2:用rlang工具更安全(推荐)

如果你的公式涉及数据框里的变量,用tidyverse生态的rlang包更安全,也更贴合dplyr的风格:

library(dplyr)
library(rlang)

a1 <- "AVG(C1) * .290"
a2 <- gsub("AVG[(]C1[)]","mean",a1)

newiris <- iris %>% 
  group_by(Species) %>% 
  summarize(n = n(),
            mean = mean(Petal.Width), 
            cv = sd(Petal.Width)/mean(Petal.Width)*100) %>% 
  mutate(cutoff = eval_tidy(parse_expr(a2)))

# 查看结果
newiris

效果说明

这两种方法都会让cutoff列正确计算出mean * 0.290的数值(也就是每个物种花瓣宽度均值乘以0.29),而不是显示字符串啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:00:25