Home > Enterprise >  How to change the year of a date POSIXct column based on thier index interval?
How to change the year of a date POSIXct column based on thier index interval?

Time:07-07

My data looks like this:

> dput(head(nAUR,50))
structure(list(date = structure(c(1483440272, 1484304241, 1484564041, 
1484823831, 1485428001, 1485687791, 1486032161, 1486291941, 1486551731, 
1486896101, 1487155881, 1487415671, 1487760031, 1488019821, 1488279601, 
1488624021, 1488883821, 1489143521, 1489488011, 1489747821, 1490007451, 
1490352021, 1490608221, 1490867781, 1491212421, 1491472221, 1491731811, 
1492076421, 1492336231, 1492595781, 1492940421, 1493200231, 1493459811, 
1493804421, 1494064231, 1494323781, 1494668431, 1494928231, 1495187811, 
1495532431, 1495792231, 1496051781, 1496396421, 1496656231, 1496915811, 
1497260421, 1497520231, 1497779781, 1498124421, 1498384231), tzone = "", class = c("POSIXct", 
"POSIXt")), layer = c("AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR", "AUR")), row.names = c(NA, 
-50L), class = c("tbl_df", "tbl", "data.frame"))

I want to change the YEAR of the dates between 2017-01-13 10:44:01 (1484304241) until 2017-03-17 10:50:21 (1489747821) to 2016. I have to do it using their position interval in the dataframe (index) because in my original data set those dates I want to change are repeated.

Any help will be much appreciated.

CodePudding user response:

You could use `year<-`() from lubridate to replace the year of a datetime object.

library(dplyr)
library(lubridate)

nAUR %>%
  mutate(date2 = if_else(between(date, 1484304241, 1489747821),
                         `year<-`(date, 2016), date))

Update
nAUR %>%
  mutate(date2 = if_else(between(row_number(), which(date == 1484304241)[1], which(date == 1489747821)[1]),
                         `year<-`(date, 2016), date))
  • Related