R data.table:如何根据条件按组对变量求和?

问题描述 投票:1回答:3

假设我有以下R data.table(虽然我很乐意使用基础R,data.frame)

library(data.table)

dt = data.table(Category=c("First","First","First","Second","Third", "Third", "Second"), Frequency=c(10,15,5,2,14,20,3), times = c(0, 0, 0, 3, 3, 1))

> dt
   Category Frequency times
1:    First        10     0
2:    First        15     0
3:    First         5     0
4:   Second         2     3
5:    Third        14     3
6:    Third        20     1
7:   Second         3     0

如果我希望按类别对频率求和,我会使用以下内容:

data[, sum(Frequency), by = Category]

但是,假设Frequency是非零并且不等于Category,那么我想用timesNA

如何根据单独列的值使此总和成为条件?

编辑:为明显的问题道歉。快速添加:如果某列的元素是字符串呢?

EG

> dt
   Category Frequency times
1:    First        ten    0
2:    First        ten    0
3:    First        five   0
4:   Second        five   3
5:    Third        five   3
6:    Third        five   1
7:   Second        ten    0

Sum()不会计算tenfive的频率

r dataframe data.table aggregate
3个回答
2
投票

记住data.table的逻辑:dt[i, j, by],即使用dt,使用i的子集行,然后计算由j分组的by

dt[times != 0 & !is.na(times), sum(Frequency), by = Category]
   Category V1
1:   Second  2
2:    Third 34

1
投票

您可以使用括号子集仅为times选择具有非零和非NA值的行,然后运行分组操作。

dt[which(dt$times > 0)][, sum(Frequency), by = Category]

1
投票

您可以使用rowsum()。

rowsum

基于分组变量给出矩阵或数据框的列和

对于分组变量的每个级别,计算跨数字矩阵对象的行的列和。 rowsum是通用的,具有数据帧的方法和向量和矩阵的默认方法。

关键词:操纵

用法

rowsum(x, group, reorder = TRUE, …)

S3 method for data.frame

rowsum(x, group, reorder = TRUE, na.rm = FALSE, …)

S3 method for default

rowsum(x, group, reorder = TRUE, na.rm = FALSE, …)

参数化矩阵,数据框或数字数据向量。允许缺少值。数字向量将被视为列向量。组

a vector or factor giving the grouping, with one element per row of x. Missing values will be treated as another group and a warning will be given.

重新排序

if TRUE, then the result will be in order of sort(unique(group)), if FALSE, it will be in the order that groups were encountered.

在我身边

logical (TRUE or FALSE). Should NA (including NaN) values be discarded?

other arguments to be passed to or from methods

细节

默认设置是将行重新排序以与tapply一致,如下例所示。重新排序不应该显着增加时间,除非有很多不同的组值且x列很少。

原始函数由Terry Therneau编写,但这是一个使用散列的新实现,对于大型矩阵来说要快得多。

要对矩阵的所有行(即单个组)求和,请使用colSums,这应该更快。

对于整数参数,形成总和的上溢/下溢导致NA。

包含总和的矩阵或数据框。每个唯一值将有一行

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.