按列值平均 r 中的数据帧数据

Average dataframe data in r by column value

我正在尝试自动对列中具有相同值的数据框中的数据进行平均。

这里是模拟数据框的代码

col1 <- c(1,1,1,2,2,2,3,3,3)
col2 <- c(10,20,15,5,8,7,30,1,25)
col3 <- c(.5,.4,.2,.2,.2,.1,.4,.5,.9)
testdf <- data.frame(col1,col2,col3)

以及该数据框的输出

testdf
  col1 col2 col3
1    1   10  0.5
2    1   20  0.4
3    1   15  0.2
4    2    5  0.2
5    2    8  0.2
6    2    7  0.1
7    3   30  0.4
8    3    1  0.5
9    3   25  0.9

我想做的是得到一个输出,它为我提供第 1 列中具有相同值的所有数据的第 2 列和第 3 列中的值的平均值(即,第 1 列时第 2 列值的平均值值为 1 时,第 3 列的平均值为 1,当第 1 列的值为 1 时,第 3 列的平均值为 .367)

我们可以使用 base R

中的 aggregate
aggregate(.~ col1, testdf, mean)

dplyr

library(dplyr)
testdf %>%
  group_by(col1) %>%
  summarise_all(mean)

data.table

library(data.table)
setDT(testdf)[, lapply(.SD, mean), by = col1]