Home > Software engineering >  Sum a sequence of dates to a dates vector in r
Sum a sequence of dates to a dates vector in r

Time:10-06

Hi and thanks for reading me Im working with a sequence of dates and I want to sum some days to a date sequence, but im getting a wrong output. The sum works with only 1 date, for example:

fechas <- c("2017-01-03", "2017-01-04", "2017-01-05")
as.Date(tail(fechas, 1)) %m % days(2)

[1] "2017-01-07"

But the expected result is:

[1] "2017-01-03", "2017-01-04", "2017-01-05", "2017-01-06", "2017-01-07"

Is there a way to obtain the correct result? I don't find anything :(

CodePudding user response:

You have to assign the result back to the last vector element.

library(lubridate)

fechas <- c("2017-01-03", "2017-01-04", "2017-01-05")
fechas <- as.Date(fechas)
fechas[length(fechas)] <- fechas[length(fechas)] %m % days(2)
fechas
#[1] "2017-01-03" "2017-01-04" "2017-01-07"

CodePudding user response:

Or may use replace

 replace(as.Date(fechas), length(fechas), as.Date(tail(fechas, 1)) %m % days(2))
[1] "2017-01-03" "2017-01-04" "2017-01-07"
  • Related