r - 使用 R 编程将虚拟行复制到引用先前日期或时间的数据集
问题描述
我是 R 编程的新手,我想在我的办公室做一些工作。我有一个数据框如下:
Sale_date Sale_State units_sold Cummulative_unit_sold
30/1/2020 Kerala 1 1
1/2/2020 Kerala 1 2
2/2/2020 Kerala 2 4
3/2/2020 Tamil Nadu 1 1
3/2/2020 Rajasthan 2 2
3/2/2020 Delhi 1 1
4/2/2020 Kerala 1 5
4/2/2020 Rajasthan 1 3
etc.... So the data is in this kind.
我想要以下格式的输出
Sale_date Sale_State units_sold Cummulative_unit_sold
30/1/2020 Kerala 1 1
1/2/2020 Kerala 1 2
2/2/2020 Kerala 2 4
3/2/2020 Tamil Nadu 1 1
3/2/2020 Rajasthan 2 2
3/2/2020 Delhi 1 1
3/2/2020 Kerala 2 4(Please observe here in rawdata no sales on 3/2/2020 for kerala state so it should copy the same data as previous date data)
4/2/2020 Kerala 1 5
4/2/2020 Rajasthan 1 3
4/2/2020 Tamil Nadu 1 1(Please observe here in rawdata no sales on 4/2/2020 for Tamil Nadu state, so it should copy the same data as previous data)
我不知道如何做到这一点。这不是直接替换 NA 值,而是我想创建一个在相应日期没有销售的 State 虚拟行,并添加以前可用的数据。
谢谢,赫曼斯
解决方案
从队列中获取问题。(; 最好是使用tidyr::complete
(variant of tidyr::expand
) 并且tidyr::fill
正如已经建议的@ulfelder:
library(tidyr)
library(dplyr)
tidyr::complete(df, Sale_date, Sale_State) %>%
# Fill by Sale_State
group_by(Sale_State) %>%
# Arrange by Date
arrange(as.Date(Sale_date, "%d/%m/%Y")) %>%
# fill with data from previous dates
tidyr::fill(units_sold, Cummulative_unit_sold) %>%
ungroup() %>%
# To get rid of obs from previous dates created by tidyr::complete
dplyr::filter(!is.na(units_sold))
#> # A tibble: 11 x 4
#> Sale_date Sale_State units_sold Cummulative_unit_sold
#> <fct> <fct> <int> <int>
#> 1 3/2/2020 Delhi 1 1
#> 2 4/2/2020 Delhi 1 1
#> 3 30/1/2020 Kerala 1 1
#> 4 1/2/2020 Kerala 1 2
#> 5 2/2/2020 Kerala 2 4
#> 6 3/2/2020 Kerala 2 4
#> 7 4/2/2020 Kerala 1 5
#> 8 3/2/2020 Rajasthan 2 2
#> 9 4/2/2020 Rajasthan 1 3
#> 10 3/2/2020 Tamil Nadu 1 1
#> 11 4/2/2020 Tamil Nadu 1 1
由reprex 包(v0.3.0)于 2020-04-19 创建
推荐阅读
- android - Android通知栏不更新所有值
- c# - c#拦截构造函数参数
- c - getchar 可以扫描的一行中有多少个字符有限制吗?
- html - Bootstrap 4 下拉菜单 - 自动调整宽度?
- php - 带连接的求和函数是用 mysql 将 laravel ORM 中条目的总和乘以 mysql
- android - 阿拉伯语自然语言处理项目的深度学习
- javascript - 对于 NoUiSlider,如何设置手柄/拇指的宽度?
- android - 如何将编辑后的 AutoCompleteTextField 值转换为表单数据
- c# - C# 我可以在 extern bool 中使用 main() 中声明的 int 吗?
- python - 抓取网页直到“下一页”被禁用