按NA在R中汇总 [英] Aggregate by NA in R
问题描述
有人知道如何通过R中的NA进行聚合.
Does anybody know how to aggregate by NA in R.
如果您使用以下示例
a <- matrix(1,5,2)
a[1:2,2] <- NA
a[3:5,2] <- 2
aggregate(a[,1], by=list(a[,2]), sum)
输出为:
Group.1 x
2 3
但是有一种方法可以使输出像这样在输出中包含NA:
But is there a way to get the output to include NAs in the output like this:
Group.1 x
2 3
NA 2
谢谢
推荐答案
您可能要考虑使用rowsum()
,而不是aggregate()
.实际上,它是为在矩阵上进行此精确运算而设计的,并且已知比aggregate()
快得多.我们可以使用addNA()
将NA
添加到a[, 2]
的因子水平.这样可以确保NA
显示为分组变量.
Instead of aggregate()
, you may want to consider rowsum()
. It is actually designed for this exact operation on matrices and is known to be much faster than aggregate()
. We can add NA
to the factor levels of a[, 2]
with addNA()
. This will assure that NA
shows up as a grouping variable.
rowsum(a[, 1], addNA(a[, 2]))
# [,1]
# 2 3
# <NA> 2
如果您仍然想使用aggregate()
,也可以合并addNA()
.
If you still want to use aggregate()
, you can incorporate addNA()
as well.
aggregate(a[, 1], list(Group = addNA(a[, 2])), sum)
# Group x
# 1 2 3
# 2 <NA> 2
还有 data.table -
library(data.table)
as.data.table(a)[, .(x = sum(V1)), by = .(Group = V2)]
# Group x
# 1: NA 2
# 2: 2 3
这篇关于按NA在R中汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!