【问题标题】:Group by with data.table using sum使用 sum 与 data.table 分组
【发布时间】: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


【解决方案1】:
library(dplyr)

dt[dt == "-" ] = NA

df <- dt %>% group_by(user) %>%
        summarise(qty = sum(!is.na(quantity)))

【讨论】:

  • 评估错误:sum 对因子没有意义。可能错误在于,当用户无法使用某个值时,除了数字之外的列也有破折号 (-)。
  • 你可以将数据包含在问题中吗?
  • 好的,所以第一步是将破折号值更改为 NA。其余的都是一样的
  • 这显示的更像是一个计数,而不是总和。你的结果与我在 python 中使用 count 相同,如果我使用 sum 给出不同的结果。
【解决方案2】:

由于历史内存限制问题,R 将数据作为因子读取。当一列中有类似字符的条目时,整列作为字符向量读入。现在 RAM 更容易获得,您可以先将数据作为字符串读入,这样它就可以保留为字符向量而不是因子。

然后在求和之前使用as.numeric 转换为实数值。无法转换为数字的字符串将转换为 NA。 na.rm=TRUE 忽略总和中的 NA。

以上所有内容:

library(data.table)
#you might want to check out the data.table::fread function to read the data directly as a data.table
x = read.table('C:/Users/user/Desktop/20180911_Dataset_b.csv',encoding = 'UTF-8',sep =',', stringsAsFactors=FALSE)

setDT(x)[, sum(as.numeric(quantity), na.rm=TRUE), by=.(user)]

参考: Is there any good reason for columns to be characters instead of factors? phiver 的有用评论 链接到 Roger Peng 的博客: https://simplystatistics.org/2015/07/24/stringsasfactors-an-unauthorized-biography/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多