R dplyr未完成滞后日期差计算



我有一个这样的数据帧:

> bp
Source: local data frame [6 x 4]
        date amount accountId type
1 2015-06-11  101.2         1    a
2 2015-06-18  101.2         1    a
3 2015-06-24  101.2         1    b
4 2015-06-11  294.0         2    a
5 2015-06-18   48.0         2    a
6 2015-06-26   10.0         2    b

它有340万行数据:

> nrow(bp)
[1] 3391874
>

我正试图使用dplyr:计算以天为单位的滞后时间差,如下所示

bp <- bp %>% group_by(accountId) %>%
  mutate(diff = as.numeric(date - lag(date)))

在我8GB内存的macbook上,R崩溃了。在64GB的Linux服务器上,代码需要花费很长时间。有解决这个问题的想法吗?

不知道你的方法出了什么问题,但有了date作为一个合适的Date对象,这里的一切都很快:

重新创建一些数据:

dat <- read.table(text="        date amount accountId type
1 2015-06-11  101.2         1    a
2 2015-06-18  101.2         1    a
3 2015-06-24  101.2         1    b
4 2015-06-11  294.0         2    a
5 2015-06-18   48.0         2    a
6 2015-06-26   10.0         2    b",header=TRUE)
dat$date <- as.Date(dat$date)

然后对340万行、1000组进行一些分析:

set.seed(1)
dat2 <- dat[sample(rownames(dat),3.4e6,replace=TRUE),]
dat2$accountId <- sample(1:1000,3.4e6,replace=TRUE)
nrow(dat2)
#[1] 3400000
length(unique(dat2$accountId))
#[1] 1000
system.time({
dat2 <- dat2 %>% group_by(accountId) %>%
  mutate(diff = as.numeric(date - lag(date)))
})
#  user  system elapsed 
#  0.38    0.03    0.40 
head(dat2[dat2$accountId==46,])
#Source: local data frame [6 x 6]
#Groups: accountId
#
#        date amount accountId type diff
#1 2015-06-24  101.2        46    b   NA
#2 2015-06-18   48.0        46    a   -6
#3 2015-06-11  294.0        46    a  -13
#4 2015-06-18  101.2        46    a    7
#5 2015-06-26   10.0        46    b    2
#6 2015-06-11  294.0        46    a    0

最新更新