I have a dataset imported from a CSV file, where the "Year" column starts from 2001 going on until 2013.
The column class however, is 'integer'.
> class(Year)
[1] "integer"
I have looked at various solutions and posts on how to make this change, but the solutions seem to be for some version of YYYY-mm-dd
/dd-mm-yyy
/mm-dd-yyyy
or to convert something like 20150521
to a date.
These are some of the commands I have tried so far, with no luck.
Year <- as.Date(Year, "%Y")
Error in charToDate(x) :
character string is not in a standard unambiguous format
as.Date(Year)
Error in as.Date.numeric(Year) : 'origin' must be supplied
as.Date(Year, Year[1])
Error in as.Date.numeric(origin, ...) : 'origin' must be supplied
as.Date(Year, "2001")
Error in charToDate(x) :
character string is not in a standard unambiguous format
as.Date(Year, 2001)
Error in as.Date.numeric(origin, ...) : 'origin' must be supplied
How can I convert a column in just the YYYY format, to a date?
##There is no way of having a date object without including a day and a month.
Even if you write:
strptime(as.character(y), "%Y")
This include a day and a month:
strptime(as.character(1999), "%Y")
[1] "1999-10-07 EEST"
As a workaround you can try keeping the year as it is or including the first day for each year and extract the year whenever you want to, like this:
###base-r:
date <- strptime("2012", "%Y")
format(date, "%Y")
[1] "2012"
as.numeric(format(date, "%Y"))
[1] 2012
###lubridate:
require(lubridate)
year(date)
[1] 2012