converting `“7-2014”`into date format and finding minimum in R

余生颓废 提交于 2020-04-18 03:40:11

问题


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 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")



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!