r - 环通环通数据帧 : How to improve performance on loop that calculates the result based on another loop through the dataset

标签 r performance loops dataframe optimization

我需要处理一个包含百万条目的庞大数据集,格式如下:

表:访问

|----------------|--------------|------------|
|   PERSON_ID    |      DATE    |  #Clicks   |
|----------------|--------------|------------|
|          1     |  2017-05-04  |          4 |
|          1     |  2018-05-04  |          1 |
|          1     |  2016-02-04  |          5 |
|          1     |  2018-05-06  |          7 |
|          2     |  2018-05-04  |          8 |
|          2     |  2018-05-16  |          1 |
|          2     |  2018-01-04  |          1 |
|          2     |  2018-02-04  |          2 |
|          ...   |  ...         |        ... |
|----------------|--------------|------------|

我想计算每天 + 30 天的点击次数。

数据
N=2,000,000
人=15,000

迭代每个人大约需要 1 秒钟,这很慢。
任何关于如何调整代码的建议将不胜感激。

我已经尝试使用 apply/lapply 但没有取得巨大成功。

代码示例:
图书馆(润滑);
#Initial Data Set
visits <- data.frame(person_id=c(1,1,1,1,2,2,2,2),
date=c(ymd("2017-05-04"),ymd("2018-05-04"),ymd("2016-02-04"),ymd("2018-05-06"),ymd("2018-05-04"),ymd("2018-05-16"),ymd("2018-01-04"),ymd("2018-02-04")),
clicks=c(4,1,5,7,8,1,1,2),
clicks_30days=0)

unique_visitors <- unique(visits$person_id)
#For Each Person
for(person_id in unique_visitors)
{
    #Subset person's records and order the, descending
    person_visits <- visits[visits$person_id == person_id,]
    person_visits <- person_visits[order(person_visits$date),]

    #For each visit count the # of clicks of the visit + all visits within visit's date + 30 days
    for(i in 1:nrow(person_visits))
    {
        search_interval <- interval( person_visits$date[i] , person_visits$date[i]+days(30)) 

        #####This is the interesting codeline#####
        calc_result <- sum(person_visits$clicks[person_visits$date %within% search_interval])** 
        ##########################################

        #save the clicks + 30 days
        visits[rownames(person_visits)[i],"clicks_30days"] <- calc_result
    }

}

任何比这更快的东西真的很感激。

最佳答案

一个 data.table使用非对等连接的方法:

library(data.table)
setDT(visits)[, clicks_30days :=
    visits[.(person_id=person_id, start=date, end=date+30L),
        on=.(person_id, date>=start, date<=end), sum(clicks), by=.EACHI]$V1
]

输出:
   person_id       date clicks clicks_30days
1:         1 2017-05-04      4             4
2:         1 2018-05-04      1             8
3:         1 2016-02-04      5             5
4:         1 2018-05-06      7             7
5:         2 2018-05-04      8             9
6:         2 2018-05-16      1             1
7:         2 2018-01-04      1             1
8:         2 2018-02-04      2             2

计时码:
library(data.table)
set.seed(0L)
npers <- 15e3L
ndates <- 150L
visits <- data.frame(person_id=rep(1L:npers, each=ndates),
    date=sample(seq(Sys.Date()-5L*365L, Sys.Date(), by="1 day"), npers*ndates, TRUE),
    clicks=sample(10, npers*ndates, TRUE))
vi <- visits

mtd0 <- function() {
    visits$person_id <- as.integer(visits$person_id) # faster for integers
    unique_visitors <- unique(visits$person_id)
    # create columns as vectors (accessing elements in loop will be fast)
    r <- visits$clicks_30days2 <- 0 # result vector
    j <- 1L
    person_id <- visits$person_id
    CL <- visits$clicks
    DATE_as_int <- as.integer(visits$date) # convert dates to integers
    for (id in unique_visitors){
        x <- person_id == id # indicates current person
        dates <- DATE_as_int[x] # take dates of this person
        clicks <- CL[x] # clicks of this person
        for (i in 1:length(dates)) {
            i_date <- dates[i] # take i-th date
            ii <- i_date <= dates & dates <= i_date + 30 # test interval
            # r[x][i] <- sum(clicks[ii]) # sum
            r[j] <- sum(clicks[ii]) # faster using one index
            j <- j + 1L
        }
    }
    visits$clicks_30days2 <- r # assigne to results
    visits
}

mtd1 <- function() {
    setDT(vi)[, clicks_30days :=
        vi[.(person_id=person_id, start=date, end=date+30L),
            on=.(person_id, date>=start, date<=end), sum(clicks), by=.EACHI]$V1
    ]
}

library(microbenchmark)
microbenchmark(mtd0(), mtd1(), times=3L)

时间:
Unit: seconds
   expr        min         lq       mean     median         uq        max neval cld
 mtd0() 144.847468 145.339189 146.358507 145.830910 147.114026 148.397141     3   b
 mtd1()   2.367768   2.398254   2.445058   2.428741   2.483703   2.538665     3  a 

关于r - 环通环通数据帧 : How to improve performance on loop that calculates the result based on another loop through the dataset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56078313/

相关文章:

r - 使用confusioMatrix时如何解决 "The data cannot have more levels than the reference"错误?

css - R Shiny 中的内联 uiOutput

r - 矢量化 stringr str_match 以删除 for 循环

java - 更快地检查我们是否可以根据给定的字母写消息

python - if语句可以是变量吗?

java - 将 for 循环示例转换为 while 循环

r - 如何在shiny app中播放本地视频?(Windows)

MySQL - 查询以查找连续范围的未使用值

c++ - 为什么 pthread 会减慢代码速度?

python - 当 DataFrame 中的一天不返回值时放入 NaN