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

rstatix中add_xy_position在双因素ANOVA的tukey_hsd结果中报错

双因素ANOVA后使用add_xy_position()报错的解决方案

问题根源

当针对Group*Time交互项执行Tukey HSD检验时,tukey_hsd()返回结果的term列为Group:Time,但原始数据框中并不存在这个合并列,add_xy_position()默认会尝试按该列分组,因此触发找不到列的错误。


解决方案

方案1:合并分组变量为单个交互列

先将Group和Time合并为一个新的分组列,再基于该列完成检验和位置计算:

library(rstatix)
library(dplyr)
library(ggplot2)

# 构建原始数据
ID <- 1:40
Time <- c(rep('d24h', 20), rep('d48h', 20))
Group <- c(rep('A', 5), rep('B', 5), rep('A', 5), rep('B', 5))
Val <- runif(40)
df <- data.frame(ID, Time, Group, Val)

# 合并Group与Time为单个交互列
df <- df %>% mutate(Group_Time = interaction(Group, Time, sep = "_"))

# 执行Tukey检验并添加位置信息
test2 <- df %>% 
  tukey_hsd(Val ~ Group_Time) %>% 
  add_xy_position(x = "Group_Time")

# 可视化示例
ggplot(df, aes(x = Group_Time, y = Val)) +
  geom_boxplot() +
  stat_pvalue_manual(test2, label = "p.adj.signif", tip.length = 0.01)

方案2:直接指定add_xy_position()参数

无需修改原始数据结构,通过明确参数告诉函数如何映射交互项分组:

# 执行Tukey检验并添加位置信息
test2 <- df %>% 
  tukey_hsd(Val ~ Group * Time) %>%
  add_xy_position(term = "Group:Time", x = c("Group", "Time"))

# 可视化示例(x轴需对应交互项组合)
ggplot(df, aes(x = interaction(Group, Time), y = Val)) +
  geom_boxplot() +
  stat_pvalue_manual(test2, label = "p.adj.signif", tip.length = 0.01)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:10:55