Home > Mobile >  change the year of a date in R
change the year of a date in R

Time:08-29

I want to rewrite the year in my data, such that from consist of a combination of the year in year column and month and day from the from column

example <- structure(list(year = 2016:2017, 
                          from = structure(c(16828L,16828L), 
                                               class = c("IDate", "Date"))), 
                     row.names = c(NA, -2L), class = c("data.table","data.frame"))

My data set is very large, so I am looking for an efficient way to do this.

CodePudding user response:

example[, date := format(from, paste0(year,"-%m-%d"))]
example
   year       from       date
1: 2016 2016-01-28 2016-01-28
2: 2017 2016-01-28 2017-01-28

CodePudding user response:

We could use lubridate year for assignment

library(lubridate)
example$from <- as.Date(example$from)
year(example$from) <- example$year

-output

> example
    year       from
   <int>     <Date>
1:  2016 2016-01-28
2:  2017 2017-01-28
  • Related