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

标签 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

关于R dplyr未完成滞后日期差计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126606/

相关文章:

r - 如何更改图例符号(关键字形)以匹配绘图符号?

python - 使用 rpy2 : cannot find R package that is installed

R dplyr : Use the function as a string in one column on the next column

r - 如何将摘要统计值添加到数据框的每一行?

r - 以 R 中的元素数量为条件删除列表

r - 计算两个时间戳之间的行数

r - 在多个 R 文件中导入相同的包

R 包在 AWS t2.micro 卡住上安装 dplyr

r - 如何使用ggplot2可视化tbl_sql数据?

r - 并排条形图与ggplot