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

R语言数据子集创建与重复测量ANOVA问题求助

重复测量ANOVA及数据子集处理问题:错误分析与修复方案

核心错误点

  • 因子转换对象错误:转换因子时误用了未定义的Data_Omnibus对象,而非目标子集df_02;且convert_as_factor并非基础R函数,易引发混乱。
  • 分组聚合语法错误:嵌套summarise的写法不符合dplyr语法,还误用了不存在的ID变量,导致警告。
  • 重复测量ANOVA数据格式问题:每个被试的Side+Rotation组合对应多个value值,不符合重复测量分析要求(每个被试在每个因子水平组合下需有唯一观测)。

修复后的完整代码

1. 正确生成数据子集并转换因子

library(dplyr)

# 加载初始数据
df <- read.table(text = '
participant_nr condition used_hand value
01 B left 13
01 C left 20
01 A left 60
01 D left 11
01 E left 17
01 B right 18
01 C right 19
01 A right 23
01 D right 18
01 E right 15
02 C left 18
02 A left 7
02 B left 12
02 D left 11
02 E left 21
02 A right 17
02 B right 20
02 C right 21
02 D right 19
02 E right 15', header = T)

# 过滤数据、生成新变量并转换为因子
df_02 <- df %>%
  filter(condition != "A") %>%
  mutate(
    Side = case_when(
      condition %in% c("B", "C") ~ "left",
      condition %in% c("D", "E") ~ "right"
    ),
    Rotation = case_when(
      condition %in% c("B", "E") ~ "low",
      condition %in% c("C", "D") ~ "high"
    )
  ) %>%
  # 直接将Side和Rotation转换为因子
  mutate(across(c(Side, Rotation), factor))

# 验证因子类型
is.factor(df_02$Side)  # 返回TRUE
is.factor(df_02$Rotation)  # 返回TRUE

2. 按被试-因子组合聚合均值

# 分组计算每个被试在Side+Rotation组合下的value均值
df_summary <- df_02 %>%
  group_by(participant_nr, Side, Rotation) %>%
  summarise(mean_value = mean(value), .groups = "drop")

3. 执行重复测量ANOVA

使用afex包的aov_car函数(需先安装afex包):

install.packages("afex")
library(afex)

# 重复测量ANOVA:Side和Rotation为被试内因子
anova_result <- aov_car(mean_value ~ Side * Rotation + Error(participant_nr/(Side*Rotation)), 
                        data = df_summary)

# 查看分析结果
print(anova_result)

说明

  • 聚合后的df_summary中,每个被试的Side和Rotation组合对应唯一的mean_value,满足重复测量ANOVA的数据格式要求。
  • 若需修改子集列名,可在mutate或summarise步骤中直接重命名,例如:rename(new_name = old_name)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:14:59