0
votes

I have data set name SE. The column YE contains years as 2009, 2010, 2011, 2012, 2013, 2014, 2015, and 2016. When i use code <-str(SE$YE) it returns as integer. How can i change these integers to date format in R

2

2 Answers

2
votes

A date in R needs to have a month and day component in addition to a year. That being said, one option here would be to arbitrarily set each year to be January 1:

years <- c(2009, 2010, 2011)
date_str <- paste0(years, '-01-01')
dates <- as.Date(date_str, "%Y-%m-%d")

If you need to work with the particular year, you can access it using format:

new_years <- format(dates, '%Y')
new_years
[1] "2009" "2010" "2011"

Demo here:

Rextester

1
votes

@Saud, following up on @Tim's answer:

you can assign the values of a data frame column simply by doing:

SE$year_as_date <-  as.Date(paste(SE$YE, '-01-01', sep=''), "%Y-%m-%d"))

This combines the two lines of code posted into one and adds the result as a new column.