首页 > 解决方案 > 用 R 计算 3 个表的平均值

问题描述

我有由 3 个文件组成的数据:file1.csv、file2.csv、file3.csv。这些文件是重复测量。每个文件包含 96 个值,排列为 12 列 (1-12) 和 8 行 (ah)。我需要计算 3 次重复中每次测量的平均值(例如 a1(file1、file2、file3)、a2 等的平均值)。我不需要按列或按行的平均值 - 我需要每个单元格的三次测量的平均值(对不起,不禁用 Excel 术语思考)。

因此,我将每个文件读入 R,然后添加一个“key”列,其中值 = rep1 为 file1,rep2 为文件 2,rep3 为文件 3,如下所示:

file1 <- file1 %>% add_column(rep = rep1)
file2 <- file2 %>% add_column(rep = rep2)
file3 <- file3 %>% add_column(rep = rep3) 

然后我使用 dplyr 的 bind_rows() 生成一个包含所有数据的 df,

all.data <- bind_rows(file1, file2, file3)

最后使用

finally <- aggregate(all.data, list(all.data$rep), mean)

我的 R 技能是初级的,我确信必须有一种更优雅、更严格的方法来做到这一点。很想知道怎么做!

标签: rdplyrtidyverse

解决方案


dplyr中,我们可以使用.id参数为每个数据帧添加唯一索引,而不是add_column单独在每个数据帧上使用。然后我们可以group_by使用这个唯一索引并用于按组summarise_all获取mean所有列。

library(dplyr)

bind_rows(file1, file2, file3, .id = "rep") %>%
   group_by(rep) %>%
   summarise_all(mean)

类似的使用方式data.table是使用rbindlist

library(data.table)
rbindlist(list(file1, file2, file3),idcol = 'rep')[, lapply(.SD, mean), rep]

推荐阅读