Date
Previous active day
。
我希望输出看起来像这样:Date蓝色 | |
10-17-2024 | |
因此,我想要该类别的第三列 | |
library(dplyr)
DF <- data.frame(
Date = rep(c("10-12-2024", "10-17-2024", "10-19-2024"), c(4L, 2L, 2L)),
category = c("Red", "Red", "Blue", "Blue", "Blue", "Blue", "Red", "Blue")
)
DF %>%
group_by(Date, category) %>%
slice_head(n=1) %>%
group_by(category) %>%
mutate(previous_active_date = lag(Date)) %>%
right_join(DF)
#> Joining with `by = join_by(Date, category)`
#> # A tibble: 8 × 3
#> # Groups: category [2]
#> Date category previous_active_date
#> <chr> <chr> <chr>
#> 1 10-12-2024 Blue <NA>
#> 2 10-12-2024 Blue <NA>
#> 3 10-12-2024 Red <NA>
#> 4 10-12-2024 Red <NA>
#> 5 10-17-2024 Blue 10-12-2024
#> 6 10-17-2024 Blue 10-12-2024
#> 7 10-19-2024 Blue 10-17-2024
#> 8 10-19-2024 Red 10-12-2024
于2025-01-31创建
10-12-2024 | ||
---|---|---|
10-12-2024 | 蓝色 | |
10-17-2024 | 蓝色 | |
10-12-2024 | ||
10-12-2024 | ||
蓝色 | ||
用Rreprexv2.1.1 | ||