r - 基于单独变量值的日期差异
问题描述
我有一个看起来像这样的数据框:
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)
解决方案
一种方法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
推荐阅读
- python-3.x - 有没有办法实现机器学习模型,可以预测给定数据集中出现次数最多的句子
- ruby-on-rails - jquery自动完成gem在应用程序中不起作用
- angular - 控制 Reactive formarray 面临的问题
- excel - VBA 将多个 Excel 工作表导出为一个 PDF 文件
- python - 连续两次 GET 请求后查找所有 DELETE 的 IP 地址
- java - TestNG 无法在 Classpath 中找到 Test 类
- react-native - 路由 'Detail' 的组件必须是 React 组件
- java - 从 Parse 访问上传的图像,给了我未定义的文件 URL 对象
- android - 尝试使用 post 方法在 android studio 中使用 laravel 护照时出错
- reactjs - 在 gh-pages 上部署 react 项目,但页面没有更新