Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)
edited by

I am having a data frame of random dates from 2008 to 2020 and their identical value

Date                     Val

September 16, 2012       32

September 19, 2014       33

January 05, 2008         26

June 07, 2017            02

December 15, 2019        03

May 28, 2020             18

I want to replace all the missing dates that are from January 01, 2008, to March 31, 2020, with value 1.

I want the following data as my output:

 Date                    Val

 January 01, 2008        1

 January 02, 2008        1

 January 03, 2008        1

 January 04, 2008        1

 January 05, 2008       26

 ........

1 Answer

0 votes
by (107k points)

For that you can simply create a data frame in R programming with the desired date range and then try to join our data frame on it and replace all the NA values with 1:

library(tidyverse)

days_seq %>% 

  left_join(df) %>% 

  mutate(Val = if_else(is.na(Val), as.integer(1), Val))

Joining, by = "Date"

# A tibble: 4,474 x 2

   DateVal

   <date>     <int>

 1 2008-01-01     1

 2 2008-01-02     1

 3 2008-01-03     1

 4 2008-01-04     1

 5 2008-01-05    33

 6 2008-01-06     1

 7 2008-01-07     1

 8 2008-01-08     1

 9 2008-01-09     1

10 2008-01-10     1

# ... with 4,464 more rows

Data

days_seq <- tibble(Date = seq(as.Date("2008/01/01"), as.Date("2020/03/31"), "days"))

df <- tibble::tribble(

                   ~Date, ~Val,

        "2012/09/16",  32L,

        "2012/09/19",  33L,

        "2008/01/05",  33L

        ) 

df$Date <- as.Date(df$Date)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...