【问题标题】:How to count the number of unique values efficiently in a repeated computation? [duplicate]如何在重复计算中有效地计算唯一值的数量? [复制]
【发布时间】:2020-07-07 07:24:30
【问题描述】:

这是我的交易数据

from_id       to_id      date_trx      week    amount
<fctr>        <fctr>     <date>        <dbl>   <dbl>
6644           6934       2005-01-01    1      700
6753           8456       2005-01-01    1      600
9242           9333       2005-01-01    1      1000
9843           9115       2005-01-01    1      900 
7075           6510       2005-01-02    1      400 
8685           7207       2005-01-02    1      1100   

...            ...        ...           ...    ...

9866           6697       2010-12-31    313    95.8
9866           5992       2010-12-31    313    139.1
9866           5797       2010-12-31    313    72.1
9866           9736       2010-12-31    313    278.9
9868           8644       2010-12-31    313    242.8
9869           8399       2010-12-31    313    372.2

我想计算每个from_ids 在每个week 上的唯一to_ids 数量:即:

data <- data %>% 
  group_by(week,from_id) %>% 
  mutate(weekly_distinct_accounts=n_distinct(to_id))

但是,计算似乎永远不会结束。这样做的有效方法是什么?我还尝试了其他功能mentioned here,但它们也无济于事

【问题讨论】:

  • 可能是aggregate(to_id ~ from_id + week, data, function(x) length(unique(x)))?
  • 试试data.tablesetDT(data)[, .(weekly_distinct_accounts=uniqueN(to_id), .(week,from_id)]
  • 感谢@GKi,这是最快的方法。

标签: r dplyr unique


【解决方案1】:

如果您想将结果存储在data 中,您可以使用ave

data$weekly_distinct_accounts <- ave(data$to_id, data$from_id, data$week
  , FUN=function(x) length(unique(x)))

或使用duplicated

data$weekly_distinct_accounts <- ave(data$to_id, data$from_id, data$week
  , FUN=function(x) sum(!duplicated(x)))

如果您只需要每组的总和,您可以使用aggregate

aggregate(to_id ~ from_id + week, data, function(x) length(unique(x)))

aggregate(to_id ~ from_id + week, data, function(x) sum(!duplicated(x)))

aggregate(to_id ~ ., unique(data[c("to_id", "from_id", "week")]), length)

【讨论】:

  • 这又需要很长时间来计算,aggregate() 更快。
  • 但是您要将结果存储在data 中吗?如果没有,那么 aggregate 和 co。会变好。如果是,您必须使用 ave 之类的东西。
  • 我通过merge()将结果添加到数据中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 2018-06-17
  • 2021-11-12
相关资源
最近更新 更多