r - 用 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 技能是初级的,我确信必须有一种更优雅、更严格的方法来做到这一点。很想知道怎么做!
解决方案
在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]
推荐阅读
- sql - 如何按州找到一个国家的第三大人口
- python-3.x - 提高 TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: index.html
- azure - Azure SignalR:HubException 方法不存在
- visual-studio-2017 - 我无法连接到 azure devops 工件 - nuget feed
- python - 如何拆分 Spark 列中所有字段的字符串并获取返回的拆分字符串列表的长度?
- reactjs - 在电子上使用 webpack 有什么好处?
- excel-formula - 将多个 IF 语句组合成一个公式
- java - 我应该使用哪个运算符来比较两个 LocalDate 值?
- environment-variables - JetBrains Rider:无法更改项目配置文件中的环境变量
- java - Android如何使用模态类的arraylist填充适配器中的详细信息