我想找出最近一次策略重组的日期,在记录日期之前。在“reconType”不是NA的日期重构策略。抱歉,如果这个问题已经得到了回答,我一直在寻找了几天,但还没有能够找到任何东西。
下面是一个可重复的示例:
strategy <- rep(c('a', 'b', 'c'), each = 3)
date <- rep(c(as.Date("2023-01-02"), as.Date("2023-01-03"), as.Date("2023-01-04")), times = 3)
reconType <- c('Annual','NA','NA','Annual','Annual','NA','NA','Annual','NA')
df1 <- data.frame(strategy, date, reconType)
df1$lastDate <- max(df1$date[!is.na(df1$Recon.Type) & df1$date < df1$date & df1$strategy == df1$strategy])
print(df1)
strategy date reconType lastDate
1 a 2023-01-02 Annual <NA>
2 a 2023-01-03 NA <NA>
3 a 2023-01-04 NA <NA>
4 b 2023-01-02 Annual <NA>
5 b 2023-01-03 Annual <NA>
6 b 2023-01-04 NA <NA>
7 c 2023-01-02 NA <NA>
8 c 2023-01-03 Annual <NA>
9 c 2023-01-04 NA <NA>
但我想要的是:
strategy date reconType lastDate
1 a 2023-01-02 Annual <NA>
2 a 2023-01-03 NA 2023-01-02
3 a 2023-01-04 NA 2023-01-02
4 b 2023-01-02 Annual <NA>
5 b 2023-01-03 Annual 2023-01-02
6 b 2023-01-04 NA 2023-01-03
7 c 2023-01-02 NA <NA>
8 c 2023-01-03 Annual <NA>
9 c 2023-01-04 NA 2023-01-03
1条答案
按热度按时间xwbd5t1u1#
使用
lag
作为条件,然后使用fill
完成群的方法。