如何在R中找到小于记录日期的最大日期?

wz3gfoph  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(78)

我想找出最近一次策略重组的日期,在记录日期之前。在“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
xwbd5t1u

xwbd5t1u1#

使用lag作为条件,然后使用fill完成群的方法。

library(dplyr)
library(tidyr)

df1 %>% 
  group_by(strategy) %>% 
  mutate(lastDate = ifelse(lag(reconType) == "Annual", as.character(lag(date)), NA)) %>% 
  fill(lastDate, .direction="down") %>% 
  ungroup()
# A tibble: 9 × 4
  strategy date       reconType lastDate  
  <chr>    <date>     <chr>     <chr>     
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

相关问题