繁体   English   中英

用不可靠的数据汇总data.table

[英]Summarize a data.table with unreliable data

我有一个记录事件的data.table ,比如用户ID,居住国家和事件。 例如,

dt <- data.table(user=c(rep(3, 5), rep(4, 5)),
                 country=c(rep(1,4),rep(2,6)),
                 event=1:10, key="user")

正如您所看到的,数据有些损坏:事件5报告用户3在国家2(或者他旅行 - 这对我来说无关紧要)。 所以当我尝试总结数据时:

dt[, country[.N] , by=user]
   user V1
1:    3  2
2:    4  2

我为用户3弄错了国家。理想情况下,我想为用户获得最常见的国家/地区以及他在那里度过的时间百分比:

   user country support
1:    3       1     0.8
2:    4       2     1.0

我怎么做?

实际数据有~10 ^ 7行,因此解决方案必须扩展(这就是我使用data.table而不是data.frame )。

其他方式:

编辑。 table(.)是罪魁祸首。 将其更改为完成data.table语法。

dt.out<- dt[, .N, by=list(user,country)][, list(country[which.max(N)], 
               max(N)/sum(N)), by=user]
setnames(dt.out, c("V1", "V2"), c("country", "support"))
#    user country support
# 1:    3       1     0.8
# 2:    4       2     1.0

使用plyrcount功能:

dt[, count(country), by = user][order(-freq),
                                list(country = x[1],
                                     support = freq[1]/sum(freq)),
                                by = user]
#   user country support
#1:    4       2     1.0
#2:    3       1     0.8

想法是计算每个用户的国家/地区,按最大频率排序,然后获取您喜欢的数据。

感谢@mnel提供的更明智的答案,它不使用额外的功能:

dt[, list(freq = .N),
     by = list(user, country)][order(-freq),
                               list(country = country[1],
                                    support = freq[1]/sum(freq)),
                               by = user]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM