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

使用ggplot2::stat_summary处理带units的R数据时报错求助

解决stat_summary处理带units数据时的drop_units报错问题

问题复现

使用stat_summary为带单位的tibble绘制均值线时触发错误,但无单位数据可正常运行:

library(tidyverse)
library(units)

tb <- tibble(a=1:8 %>% set_units(kg),b=1:8) 
tb_unitless <- drop_units(tb)

# 无单位数据正常运行
ggplot(tb_unitless,aes(x=b,y=a)) + 
stat_summary(fun = "mean", geom="hline",aes(yintercept=after_stat(y)))

# 带单位数据报错
ggplot(tb,aes(x=b,y=a)) + 
stat_summary(fun = "mean", geom="hline",aes(yintercept=after_stat(y)))

报错信息:

Error in `stat_summary()`:
! Problem while mapping stat to aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `UseMethod()`:
! no applicable method for 'drop_units' applied to an object of class "c('double', 'numeric')"

解决方案

方法1:手动计算带单位的均值,直接使用geom_hline

绕过stat_summary的内部处理逻辑,提前计算保留单位的均值,再传递给geom_hline:

# 计算带单位的均值
mean_a <- mean(tb$a)

ggplot(tb, aes(x = b, y = a)) +
  geom_hline(aes(yintercept = mean_a))

方法2:显式为stat_summary结果补全单位

通过自定义函数确保计算结果保留单位属性,或在美学映射中重新赋值单位:

ggplot(tb, aes(x = b, y = a)) +
  stat_summary(
    fun = function(x) mean(x),
    geom = "hline",
    aes(yintercept = after_stat(set_units(y, get_units(tb$a))))
  )

错误原因

该问题属于ggplot2与units包的版本兼容性问题:stat_summary在计算均值后,内部处理过程意外剥离了数值的单位属性,后续代码试图对普通数值调用仅适用于带单位对象的drop_units方法,从而触发错误。旧版本的包组合可能未存在此问题,版本更新后逻辑变化导致冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:40:13