问题
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 :)
回答1:
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)
回答2:
You can put an arbitrary date in the vector and convert it into date to calculate min
.
Or you can also use zoo
s 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")
回答3:
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")
来源:https://stackoverflow.com/questions/61224775/converting-7-2014into-date-format-and-finding-minimum-in-r