为什么一些分组值在 aggregate() 中被丢弃?
Why are some grouping values dropped in aggregate()?
当我像下面那样聚合数据框时,我注意到一些按列值聚合的值被删除了
set.seed(100)
b <- data.frame(id=sample(1:3, 5, replace=TRUE),
prop1=sample(c(TRUE,FALSE),5, replace = TRUE),
prop2= sample(c(TRUE,FALSE,NA), 5, replace= TRUE))
> b
id prop1 prop2
1 3 FALSE TRUE
2 1 FALSE NA
3 2 FALSE NA
4 2 FALSE FALSE
5 3 TRUE TRUE
> aggregate(. ~ id, b, function(x) { length(x[x == TRUE])/length(x)})
id prop1 prop2
1 2 0.0 0
2 3 0.5 1
这里的 id
1 发生了什么事 - 为什么它被删除了?
如果你查看aggregate
的帮助,你会看到有一个参数指定如何处理缺失值:na.action
。
经过一些试验后,我找到了一个可以重现您的问题的种子 ;)
set.seed(3)
b <- data.frame(id=sample(1:6, 10, replace=TRUE),
prop1=sample(c(TRUE,FALSE),10, replace = TRUE),
prop2= sample(c(TRUE,FALSE,NA), 10, replace= TRUE))
b
id prop1 prop2
1 3 TRUE TRUE
2 6 TRUE NA
3 4 FALSE FALSE
4 4 FALSE TRUE
5 4 TRUE NA
6 3 TRUE NA
7 2 FALSE FALSE
8 3 TRUE FALSE
9 3 TRUE TRUE
10 4 FALSE FALSE
所以我们有这个 id 6。
这应该可以做到:
aggregate(. ~ id, b, function(x) { sum(x,na.rm=TRUE)/length(x)}, na.action=NULL)
id prop1 prop2
1 2 0.00 0.00
2 3 1.00 0.50
3 4 0.25 0.25
4 6 1.00 0.00
当我像下面那样聚合数据框时,我注意到一些按列值聚合的值被删除了
set.seed(100)
b <- data.frame(id=sample(1:3, 5, replace=TRUE),
prop1=sample(c(TRUE,FALSE),5, replace = TRUE),
prop2= sample(c(TRUE,FALSE,NA), 5, replace= TRUE))
> b
id prop1 prop2
1 3 FALSE TRUE
2 1 FALSE NA
3 2 FALSE NA
4 2 FALSE FALSE
5 3 TRUE TRUE
> aggregate(. ~ id, b, function(x) { length(x[x == TRUE])/length(x)})
id prop1 prop2
1 2 0.0 0
2 3 0.5 1
这里的 id
1 发生了什么事 - 为什么它被删除了?
如果你查看aggregate
的帮助,你会看到有一个参数指定如何处理缺失值:na.action
。
经过一些试验后,我找到了一个可以重现您的问题的种子 ;)
set.seed(3)
b <- data.frame(id=sample(1:6, 10, replace=TRUE),
prop1=sample(c(TRUE,FALSE),10, replace = TRUE),
prop2= sample(c(TRUE,FALSE,NA), 10, replace= TRUE))
b
id prop1 prop2
1 3 TRUE TRUE
2 6 TRUE NA
3 4 FALSE FALSE
4 4 FALSE TRUE
5 4 TRUE NA
6 3 TRUE NA
7 2 FALSE FALSE
8 3 TRUE FALSE
9 3 TRUE TRUE
10 4 FALSE FALSE
所以我们有这个 id 6。
这应该可以做到:
aggregate(. ~ id, b, function(x) { sum(x,na.rm=TRUE)/length(x)}, na.action=NULL)
id prop1 prop2
1 2 0.00 0.00
2 3 1.00 0.50
3 4 0.25 0.25
4 6 1.00 0.00