首页 > 解决方案 > 用R中的重复测量/长数据计算汇总统计

问题描述

抱歉,如果在其他地方问过这个问题/如果我使用了错误的术语,我一直在尝试寻找正确的方法来做到这一点,但到目前为止还没有成功。

我有一个使用重复测量结果的具有 3 个实验条件的实验设计(每个参与者完成 4 个试验)。我目前拥有的数据是长格式的(每个参与者 ID 重复 4 次)。我正在尝试计算人口统计变量(年龄、性别、状况等)的汇总统计数据,但由于没有更好的词,我无法弄清楚如何将每个参与者的行折叠/合并在一起以获得频率数据和/或汇总统计。

下面我有一个模拟数据集

require(tidyverse)
require(summarytools)
require(skimr)
require(lme4)
require(wakefield) #to simulate age distribution
require(reshape2)

id <- rep(1:150, each = 4)
age <- rep(age(150, x = 18:21), each = 4)
gender <- rep(c("male", "male", "male", "male", "female", "female","female","female"), each = 25, times = 3)
condition <- rep(c("condition_1", "condition_2", "condition_3"), each = 4, times = 50) #condition
control_1 <- rep(c("order_1", "order_2"), each = 4, length.out = 600) # control variable for counterbalancing
control_2 <- rep(c("group_1", "group_2"), each = 75, length.out = 600) control variable for counterbalancing
test1_trial <- rep(c("trial_1", "trial_2", "trial_3", "trial_4"), each = 1, length.out = 600)
test1_outcome <- rbinom(600, 1, 0.5) # actual data
test2_trial <- rep(c("trial_1", "trial_2", "trial_3", "trial_4"), each = 1, length.out = 600)
test2_outcome <- rbinom(600, 1, 0.5) # actual data

dat <- data.frame(id, age, gender, condition, control_1, control_2, test1_trial, test1_outcome, test2_trial, test2_outcome)

我试过像这样使用 group_by

dat %>% 
  group_by(id) %>% 
  freq(age)

但这给了我每个 id 作为一个单独的组,这显然对汇总统计没有帮助。

我也尝试使用 summarise_all 但无法让它工作

dat$id <- as.factor(dat$id)

dat %>% 
  select(id, age)
  group_by(id) %>% 
  summarise_all(funs(sum))

Error in UseMethod("group_by") : no applicable method for 'group_by' applied to an object of class "c('integer', 'numeric')"

对于汇总统计数据,我不关心实际数据(即 test1_outcome 和 test2_outcome),我只想能够计算例如平均年龄、每个条件的参与者数量等。有没有办法我可以以某种方式选择只是控制/人口变量并为每个参与者折叠它们?

为基本问题道歉,我通常不使用重复测量设计,因此对长格式数据不太熟悉。

标签: rdataframedplyrreshape2

解决方案


如果您的人口统计数据在治疗轮次中没有变化,您可以按 id 运行 distinct() 或 unique(),类似于 Jon Spring 的建议,如下所示:

dat %>% 
distinct(id, age, gender)

然后,您可以按条件折叠以通过此变量或您想要的任何其他变量以及参与者数量获取摘要统计信息:

dat %>% 
distinct(id, age, gender, condition) %>% 
group_by(condition, gender) %>% 
mutate(n = n()) %>% 
summarise_all( .funs = c(mean))

推荐阅读