【发布时间】:2019-09-25 13:30:15
【问题描述】:
我有一个带有日期列的数据框(或 data.table)。我想为所有前面的记录(不包括当前记录)创建一个具有最大日期的新列
谢谢。
以下代码创建一个列(premax),其中包含当前行之前的行的“end”的最大值(cummax)。我想在“结束”是日期变量的情况下执行此操作。我还希望能够排除当前行(想想 sql 的行边界)。看来 cumsum 不支持日期类型。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
id<-c(1,1,1,1,2,2,2,2)
start<-c(1,2,3,4,2,3, 4,5)
end<- c(2,5,4,7,4,10,6,12)
df<-data.frame(id,start,end)
df %>% mutate(premax=cummax(end))
#> id start end premax
#> 1 1 1 2 2
#> 2 1 2 5 5
#> 3 1 3 4 5
#> 4 1 4 7 7
#> 5 2 2 4 7
#> 6 2 3 10 10
#> 7 2 4 6 10
#> 8 2 5 12 12
【问题讨论】:
-
这是在 R 中抱歉问题不完整。 (陷入我自己的小世界)。
-
请至少给出一个示例数据集,参见minimal reproducible example,以便人们准确回答。