0

I have date stored as character in the vector date

> head(date)
[1] "7-2014"  "1-2018"  "11-2014" "7-2014"  "1-2018"  "1-2018" 

and want to convert it to date and find its minimum. I used as.Date as explained here

as.Date(date, "%m-%Y")

but only get NA as result. Why is this not working?

I want to find the minimum date in the column. If you know of a better approach, enlighten me :)

Nneka
  • 1,764
  • 2
  • 15
  • 39

3 Answers3

0

as.Date requires a day of the month:

date <- c("7-2014",  "1-2018",  "11-2014", "7-2014",  "1-2018",  "1-2018")
as.Date(paste0("1-", date), "%d-%m-%Y")
#> [1] "2014-07-01" "2018-01-01" "2014-11-01" "2014-07-01" "2018-01-01"
#> [6] "2018-01-01"

Created on 2020-04-15 by the reprex package (v0.3.0)

Simon Woodward
  • 1,946
  • 1
  • 16
  • 24
0

You can put an arbitrary date in the vector and convert it into date to calculate min.

Or you can also use zoos yearmon

min(zoo::as.yearmon(x, "%m-%Y"))
#[1] "Jul 2014"

data

x <- c("7-2014" , "1-2018",  "11-2014", "7-2014",  "1-2018",  "1-2018")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can also use lubridate after appending a day at the end

library(lubridate)
min(myd(paste0(x, '-1')))

data

x <- c("7-2014" , "1-2018",  "11-2014", "7-2014",  "1-2018",  "1-2018")
akrun
  • 874,273
  • 37
  • 540
  • 662