首页 > 解决方案 > 基于单独变量值的日期差异

问题描述

我有一个看起来像这样的数据框:

        Date Value Value_Increase
1 2020-05-01     5          FALSE
2 2020-05-02     4          FALSE
3 2020-05-03    10           TRUE
4 2020-05-04     9          FALSE
5 2020-05-05     7          FALSE
6 2020-05-06    12           TRUE
7 2020-05-07     8          FALSE

我想创建一个新列,提供自“值”列增加以来的天数。

结果看起来像下面的数据框。

        Date Value Value_Increase Days_Since_Value_Increase
1 2020-05-01     5          FALSE                        NA
2 2020-05-02     4          FALSE                        NA
3 2020-05-03    10           TRUE                        NA
4 2020-05-04     9          FALSE                         1
5 2020-05-05     7          FALSE                         2
6 2020-05-06    12           TRUE                         3
7 2020-05-07     8          FALSE                         1

感谢您提供任何帮助或建议,尤其是那些可能使用 dplyr 方法的人。

创建工作示例的代码:

Date <- as.Date(c("2020-05-01", "2020-05-02", "2020-05-03", "2020-05-04", "2020-05-05", "2020-05-06", "2020-05-07"))
Value <- c(5, 4, 10, 9, 7, 12, 8)
Value_Increase <- c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE)
df <- data.frame(Date, Value, Value_Increase, Days_Since_Value_Increase)

标签: rdataframedatetimetimedplyr

解决方案


一种方法tidyverse是将您的结果分组,cumsum以便自上次值增加以来的天数将由row_number()组内的 表示。这假设一天的行之间存在差异。

library(tidyverse)

df %>%
  group_by(g = cumsum(lag(Value_Increase, default = 0))) %>%
  mutate(Days_Since_Value_Increase = ifelse(g == 0, NA, row_number()))

输出

# A tibble: 7 x 5
# Groups:   g [3]
  Date       Value Value_Increase     g Days_Since_Value_Increase
  <date>     <dbl> <lgl>          <dbl>                     <int>
1 2020-05-01     5 FALSE              0                        NA
2 2020-05-02     4 FALSE              0                        NA
3 2020-05-03    10 TRUE               0                        NA
4 2020-05-04     9 FALSE              1                         1
5 2020-05-05     7 FALSE              1                         2
6 2020-05-06    12 TRUE               1                         3
7 2020-05-07     8 FALSE              2                         1

推荐阅读