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

R中使用dplyr mutate调用自定义函数生成数据框新列报错如何解决

问题原因说明

  • 自定义函数存在笔误:温度上限判断逻辑中误将自定义变量tmax写为max,max是R内置的取最大值函数,数值与函数对象直接比较会触发类型错误,这是方案2报错的核心原因
  • pmap语法使用错误:purrr::pmap需要第一个参数传入待逐行迭代的列集合,且函数传递逻辑错误,这是方案1报错的原因

修正后可运行代码

首先修正自定义函数:

# 修正后的温度计算函数
tb <- 11
topt <- 30
tmax <- 42

tt <- function(tmx, tmn, tb, topt, tmax){
  tmean <- (tmx + tmn) / 2
  t1 <- 0
  if(tmean > tb & tmean <= topt) {
    t1 = tmean - tb
  }
  if(tmean > topt & tmean < tmax) {
    t1 = (topt - tb) / (topt - tmax) * (tmean - tmax)
  }
  return(t1)
}

实现方案1:基于rowwise的逐行运算(语法更简洁)

library(dplyr)
tt.example <- data1 %>%
  rowwise() %>%
  mutate(tt_daily = tt(tmx, tmn, tb, topt, tmax)) %>%
  ungroup() # 运算完成后取消行分组,避免影响后续数据操作

实现方案2:基于purrr::pmap的逐行运算

library(dplyr)
library(purrr)
tt.example <- data1 %>%
  mutate(tt_daily = pmap_dbl(
    .l = list(tmx, tmn), # 指定需要逐行遍历的列
    .f = ~ tt(.x, .y, tb, topt, tmax) # tb/topt/tmax为全局固定参数,不需要遍历
  ))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:57:02