首页 > 解决方案 > 使用 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 虚拟行,并添加以前可用的数据。

谢谢,赫曼斯

标签: r

解决方案


从队列中获取问题。(; 最好是使用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 创建


推荐阅读