Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

r - How to add only missing Dates in Dataframe

I have below mentioned data frame:

Date        Val1     Val2
2018-04-01  125      0.05
2018-04-03  458      2.99
2018-04-05  354      1.25

I want to add only missing dates considering Sys.Date() (Here for example Sys.Date() is 2018-04-06) in dataframe with corresponding val1 and val2 as 0.

I have tried:

t2<-merge(data.frame(Date= seq(min(ymd(t1$Date)), max(ymd(date)), by = "days")), t1, by = "Date", all = TRUE)

Required Dataframe:

Date        Val1     Val2
2018-04-01  125      0.05
2018-04-02  0        0
2018-04-03  458      2.99
2018-04-04  0        0
2018-04-05  354      1.25
2018-04-06  0        0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This could be done with complete

library(tidyverse)
df1 %>%
    complete(Date = seq(Date[1], Sys.Date(), by = "1 day"),
                fill = list(Val1 = 0, Val2 = 0))

If we need to pass multiple variables for the fill, create the list of columns that we need to fill

nm1 <- setdiff(names(df1), "Date") #in this example excluding the Date
nm2 <- setNames(as.list(rep(0, length(nm1))), nm1)

and then pass that as argument for the fill

df1 %>% 
     complete(Date = seq(Date[1], Sys.Date(), by = "1 day"), fill = nm2)
# A tibble: 35 x 3
#   Date        Val1  Val2
#   <date>     <dbl> <dbl>
# 1 2018-04-01   125  0.05
# 2 2018-04-02     0  0   
# 3 2018-04-03   458  2.99
# 4 2018-04-04     0  0   
# 5 2018-04-05   354  1.25
# 6 2018-04-06     0  0   
# 7 2018-04-07     0  0   
# 8 2018-04-08     0  0   
# 9 2018-04-09     0  0   
#10 2018-04-10     0  0   
# ... with 25 more rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...