0

I have encountered a difficulty, trying to use the as.Date function (in R) on a data frame to preserve date format. The date column consists of blank cells (i.e. missing dates) and observed dates in the format month/year (e.g. 8/2019).

As mentioned earlier, I have tried using the as.Date function but the column for the dates turns blank completely (i.e. no dates are reported). Below is the code I am using:

df$date <- df$date<- as.Date(df$date, format='%m/%Y') #df is the data frame

The expected results should have the observed dates and the missing dates replaced with NA. I greatly appreciate your help.

T Richard
  • 525
  • 2
  • 9

1 Answers1

0

You need to add a date component to make it a complete date. Once you do that it is easy to convert it into an actual date object

as.Date(paste0("1/", "8/2019"), "%d/%m/%Y")
#[1] "2019-08-01"

Or using dmy from lubridate

lubridate::dmy(paste0("1/", "8/2019"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I have used this but nothing changes in my output. I still observe blank cells on the date column. I would like to understand the cause of this in order to fix it. Thanks Ronak – T Richard Aug 28 '19 at 00:32
  • @TRichard Did you assign the result back `df$Date <- as.Date(paste0("1/", df$date), format="%d/%m/%Y")` ? If it doesn't work then can you share `dput` of your data to exactly understand the problem? `dput(head(df))` – Ronak Shah Aug 28 '19 at 00:35