【发布时间】:2019-02-18 00:11:22
【问题描述】:
我有一个数据框,我想按用户分组并找到数量总和。
library(data.table)
x = read.table('C:/Users/user/Desktop/20180911_Dataset_b.csv',encoding = 'UTF-8',sep =',')
dt = data.table(x)
colnames(dt)
"dates_d" "user" "proj" "quantity"
quantity的专栏是这样的:
quantity
1
34
12
13
3
12
-
11
1
我听说data.table library 很快,所以我想用它。
我已经在 Python 中实现了,但不知道如何在 R 中实现。
【问题讨论】:
-
请参考此链接:stackoverflow.com/questions/1299871/… 以获得基准测试结果。
-
你可能想使用
read.table(..., stringsAsFactors=FALSE)然后dt[, sum(quantity), by=.(user)] -
@chinsoon12 给
Type 'character' not supported by GForce sum (gsum). Either add the prefix base::sum(.) or turn off GForce optimization using options(datatable.optimize=1) -
你可以先转换成数字。
dt[, sum(as.numeric(quantity), na.rm=TRUE), by=.(user)] -
这是正确的。回答一下,我会接受的。只是几个问题:'-' 破折号是如何变成 0 的?我的意思是这很好,但是字符串 asfactors 是否将其变为 na 然后 na.rm 将其变为 0?在你的回答中解释这些棘手的部分。谢谢
标签: r group-by data.table