Home > other >  How to fill dataframe in R with months and NA values
How to fill dataframe in R with months and NA values

Time:11-08

This is my dataframe:

df <- structure(list(month_date = structure(c(19117, 19149, 19180, 
19212, 19244, 19275), class = "Date"), Values = c(9693, 10227, 
10742, 11672, 10565, 10080)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

I need to increse the column month_date until "2023-12-01" with "NA" values.

The output should be a datframe with months until "2023-12-01" and on the Values column filled by "NA" values starting on "2022-11-01".

How can I do this?

CodePudding user response:

library(tidyr)
complete(df, month_date = seq(min(month_date), as.Date("2023-12-01"), 
      by = '1 day'))

CodePudding user response:

You can also create a separate dataframe/tibble if for some reason you do not want to use tidyr()

add <- data.frame(month_date = seq.Date(as.Date("2022-11-01"), as.Date("2023-12-01"), by = "month"), Values = NA)

final <- rbind(df, add)
  •  Tags:  
  • r
  • Related