【问题标题】:R 'aggregate' runs out of memoryR“聚合”内存不足
【发布时间】:2013-07-23 08:27:37
【问题描述】:

我有一个关于微博的数据集(600 Mb 和 5038720 次观察),我试图弄清楚一个用户在一小时内发布了多少推文(推文与一个相同的中间数)。数据集如下所示:

head(mydata)

       uid              mid    year month date hour min sec
1738914174 3342412291119279 2011     8    3   21   4  12
1738914174 3342413045470746 2011     8    3   21   7  12
1738914174 3342823219232783 2011     8    5    0  17   5
1738914174 3343095924467484 2011     8    5   18  20  43
1738914174 3343131303394795 2011     8    5   20  41  18
1738914174 3343386263030889 2011     8    6   13  34  25

这是我的代码:

count <- function(x) {
length(unique(na.omit(x)))
}
attach(mydata)
hourPost <- aggregate(mid, by=list(uid, hour), FUN=count)

它在那里挂了大约半个小时,我发现所有的真实内存(24 Gb)都被使用了,它开始使用虚拟内存。知道为什么这个小任务会消耗这么多时间和内存,我应该如何改进它?提前致谢!

【问题讨论】:

    标签: r memory aggregate


    【解决方案1】:

    使用包data.table:

    mydata <- read.table(text="       uid              mid    year month date hour min sec
    1738914174 3342412291119279 2011     8    3   21   4  12
    1738914174 3342413045470746 2011     8    3   21   7  12
    1738914174 3342823219232783 2011     8    5    0  17   5
    1738914174 3343095924467484 2011     8    5   18  20  43
    1738914174 3343131303394795 2011     8    5   20  41  18
    1738914174 3343386263030889 2011     8    6   13  34  25", 
    header=TRUE, colClasses = c(rep("character",2),rep("numeric",6)), 
    stringsAsFactors = FALSE)
    
    library(data.table)
    DT <- data.table(mydata)
    DT[, length(unique(na.omit(mid))), by=list(uid,hour)]
    

    aggregate 将分组变量强制转换为因子,这可能会占用您的记忆(我假设您有多个级别的 uid)。

    可能有更多的优化潜力,但您没有提供有代表性的测试用例。

    【讨论】:

    • 非常感谢!我只是按照你的建议做了,不到一分钟就返回了结果!
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多