r - 在现有 df 中连续完成列表
问题描述
我有这个数据框:
> df
date val cday
<date> <dbl> <dbl>
2019-12-01 1 NA
2019-12-02 0 NA
2019-12-03 1 NA
2019-12-04 0 1
2019-12-05 0 NA
2019-12-06 0 NA
2019-12-07 1 1
2019-12-08 2 NA
2019-12-09 3 NA
2019-12-10 3 NA
# … with 246 more rows
我想在 30 岁之前df$cday
连续完成df$cday == 1
最多 30次,df$cday == 1
我想再次从 1 开始计数NAs
我想保留的所有其他人。
结果应如下所示:
> df
date val cday
<date> <dbl> <dbl>
2019-12-01 1 NA
2019-12-02 0 NA
2019-12-03 1 NA
2019-12-04 0 1
2019-12-05 0 2
2019-12-06 0 3
2019-12-07 1 1
2019-12-08 2 2
2019-12-09 3 3
2019-12-10 3 4
# … with 246 more rows
可能有一个简单的解决方案,但我找不到任何搜索。我会非常感谢一些提示!
解决方案
一种方法是:
library(dplyr)
df %>%
group_by(idx = cumsum(!is.na(cday))) %>%
mutate(cday = case_when(!all(is.na(cday)) ~ row_number())) %>%
ungroup %>% select(-idx)
输出(带有示例的可见部分):
# A tibble: 10 x 3
date val cday
<fct> <int> <int>
1 2019-12-01 1 NA
2 2019-12-02 0 NA
3 2019-12-03 1 NA
4 2019-12-04 0 1
5 2019-12-05 0 2
6 2019-12-06 0 3
7 2019-12-07 1 1
8 2019-12-08 2 2
9 2019-12-09 3 3
10 2019-12-10 3 4
上面的代码假设您当前所有的非缺失案例都是 1。如果序列也可以以其他整数开头,您可以调整:
df %>%
group_by(idx = cumsum(!is.na(cday))) %>%
mutate(cday = case_when(!all(is.na(cday)) ~ cday[1] + (row_number() - 1))) %>%
ungroup %>% select(-idx)
推荐阅读
- php - 在 PHP 表单中,字符串输入在提交后被转换为 0
- python - numpy 作者如何决定是否将函数放入 numpy.* 与 numpy.ndarray.* 中?
- go - 如何在 Visual Studio 代码中允许“供应商”文件夹支持
- html - Css Position:sticky 仅在 MOBILE 中不起作用
- python - 如何从 .gitlab-ci.yml 文件中提取单个管道名称?
- php - 如果脚本被注入到私有页面中,XSS 错误仍然很危险吗?
- python - Pandas 列的字典并选择正确的值
- ansible - ansible 检查文件名与不同的字符串大小写,我可以实现 if/else 吗?
- r - 如何在特定字符串上添加字符?
- c - 我怎样才能弄清楚为什么函数有分段错误