如何根据每个ID在R中汇总table
How to summarize table in R, according to each ID
所以我有一个 table 结构如下
id V1 V2
101, 500, 1
101, 600, 1
102, 300, 0
102, 300, 0
102, 400, 0
102, 100, 1
103, 200, 0
103, 400, 0
104, 200, 1
基本上对于每个 id,我想计算 V1 的平均值和 V2 的总和,所以新的 table 应该是这样的
id V1 V2
101, 550, 2
102, 275, 1
103, 400, 0
104, 200, 1
如果有人能提供帮助,我将不胜感激。
对于这类问题,我们可以使用聚合函数之一。在这里,我使用 dplyr
。我们 group_by
'id' 和 summarise
'V1' 和 'V2' 列以及相应列的 mean
和 sum
。
library(dplyr)
df1 %>%
group_by(id) %>%
summarise(V1=mean(V1, na.rm=TRUE), V2= sum(V2, na.rm=TRUE))
# id V1 V2
#1 101 550 2
#2 102 275 1
#3 103 300 0
#4 104 200 1
或者另一个选项是 data.table
。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
),按 'id' 分组,我们得到列的 mean
和 sum
。
library(data.table)
setDT(df1)[, list(V1=mean(V1, na.rm=TRUE), V2= sum(V2, na.rm=TRUE)), by = id]
# id V1 V2
#1: 101 550 2
#2: 102 275 1
#3: 103 300 0
#4: 104 200 1
或使用base R
do.call(rbind, by(df1, df1[1], FUN=function(x)
data.frame(id=x[1,1], V1= mean(x[,2], na.rm=TRUE),
V2=sum(x[,3], na.rm=TRUE))))
所以我有一个 table 结构如下
id V1 V2
101, 500, 1
101, 600, 1
102, 300, 0
102, 300, 0
102, 400, 0
102, 100, 1
103, 200, 0
103, 400, 0
104, 200, 1
基本上对于每个 id,我想计算 V1 的平均值和 V2 的总和,所以新的 table 应该是这样的
id V1 V2
101, 550, 2
102, 275, 1
103, 400, 0
104, 200, 1
如果有人能提供帮助,我将不胜感激。
对于这类问题,我们可以使用聚合函数之一。在这里,我使用 dplyr
。我们 group_by
'id' 和 summarise
'V1' 和 'V2' 列以及相应列的 mean
和 sum
。
library(dplyr)
df1 %>%
group_by(id) %>%
summarise(V1=mean(V1, na.rm=TRUE), V2= sum(V2, na.rm=TRUE))
# id V1 V2
#1 101 550 2
#2 102 275 1
#3 103 300 0
#4 104 200 1
或者另一个选项是 data.table
。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
),按 'id' 分组,我们得到列的 mean
和 sum
。
library(data.table)
setDT(df1)[, list(V1=mean(V1, na.rm=TRUE), V2= sum(V2, na.rm=TRUE)), by = id]
# id V1 V2
#1: 101 550 2
#2: 102 275 1
#3: 103 300 0
#4: 104 200 1
或使用base R
do.call(rbind, by(df1, df1[1], FUN=function(x)
data.frame(id=x[1,1], V1= mean(x[,2], na.rm=TRUE),
V2=sum(x[,3], na.rm=TRUE))))