How to convert four digit Year values to Date type in R? -


i've integer column in dataset has 4 digit year values, like:

 2001 2002 2002 2002 2003 2005  

i trying convert 4 digit year value date type.

the code i'm using is:

year <- as.date(as.character(data_file$evtyear), format="%y") 

but output is:

"2001-05-15" "2002-05-15" "2002-05-15" "2002-05-15" "2003-05-15" "2005-05-15" 

this giving wrong output. it's giving 2 year values in 1 date (both 2001 , 15).

i want convert 4 digit year part original data 'year' in date type. expected out put simply:

2001 2002 2002 2002 2003 2005  

but class should of date type.

how achieve in r?

based on comments turned out person asking question did not need change numeric year "date" class; nevertheless, question asked how here answer.

here few ways create "date" class object 4 digit numeric year. use as.date:

yrs <- c(2001, 2002, 2002, 2002, 2003, 2005) 

1) isodate

as.date(isodate(yrs, 1, 1))  # beginning of year as.date(isodate(yrs, 12, 31))  # end of year 

this isodate solution bit tricky because creates intermediate posixct object time zone problems exist. might prefer 1 of following.

2) paste

as.date(paste(yrs, 1, 1, sep = "-")) # beginning of year as.date(paste(yrs, 12, 31, sep = "-")) # end of year 

3) zoo::as.yearmon

library(zoo)  as.date(as.yearmon(yrs)) # beginning of year as.date(as.yearmon(yrs) + 11/12, frac = 1) # end of year 

note: if y result of above format(y, "%y") gives character year , as.numeric(format(y, "%y")) gives numeric year.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -