如何使用前一天的值填充缺失值? (使用dplyr -spread)

时间:2017-07-23 21:49:41

标签: r

我的数据输出是填充值,其中包含季度缺失天数的NA。我的数据如下。

library(dplyr)
account = rep(30005)
qtr = c('Cur_QTR','Cur_QTR','Cur_QTR','Last_QTR','Last_QTR', 'Last_QTR','Last_QTR',
                       'Last_QTR',
                       'same_last',
                       'same_last',
                       'same_last',
                       'same_last',
                       'same_last',
                       'same_last',
                       'same_last')
day = c(1,3,5,1,2,3,4,5,1,2,3,4,5,6,7)
value = c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75)

df = data.frame(account,qtr,day,value)

df1 <- df %>%
  spread(key=qtr, value = value)

但是我喜欢看看输出没有NA。可能吗?请帮忙。

account   day cur_QTR Last_QTR    same_last
30005 1   5   20  45
30005 2   5   25  50
30005 3   10  30  55
30005 4   10  35  60
30005 5   15  40  65
30005 6   15  40  70
30005 7   15  40  75

1 个答案:

答案 0 :(得分:2)

我们可以使用fill函数

df %>% 
   spread(qtr, value) %>%
   fill(Cur_QTR, Last_QTR)
#   account day Cur_QTR Last_QTR same_last
#1   30005   1       5       20        45
#2   30005   2       5       25        50
#3   30005   3      10       30        55
#4   30005   4      10       35        60
#5   30005   5      15       40        65
#6   30005   6      15       40        70
#7   30005   7      15       40        75