Home > Net >  Inserting Previous Dates in R Vector
Inserting Previous Dates in R Vector

Time:11-05

I'm trying to insert the previous date for every date in a vector in R. This is my current vector:

[1] "1990-02-08" "1990-03-28" "1990-05-16" "1990-07-05" "1990-07-13" "1990-08-22" "1990-10-03"
[8] "1990-10-29" "1990-11-14" "1990-12-07" "1990-12-18" "1991-01-08" "1991-02-01" "1991-02-07"

I'm trying to get the following:

[1] "1990-02-07" "1990-02-08" "1990-03-27" "1990-03-28" "1990-05-15" "1990-05-16" "1990-07-05"  

ect.

I tried the following:

dates_lagged = as.Date(dates)-1
dates_combined = c(date, dates_lagged)

However, with this method, some dates are not getting lagged. Is there a better way to do this?

Edit: to answer the comment, this is my code (replaced CSV with its starting values):

FOMC <- read_csv(file = c("x", "1990-02-08", "1990-03-28", "1990-05-16", "1990-07-05", "1990-07-13", "1990-08-22", "1990-10-03",
                          "1990-10-29", "1990-11-14", "1990-12-07"))
FOMC$x <- as.Date(FOMC$x, format = "%Y-%m-%d")
colnames(FOMC) <- "Date"
dates_vector <- FOMC[["Date"]]
FOMC = as.vector(as.Date(dates_vector))
dates_lagged = as.Date(FOMC)-1
dates_combined = c(FOMC, dates_lagged)
as.Date(dates_combined)

For some reason, there is no "1990-10-28" before "1990-10-29" for example, and I can't figure out why.

CodePudding user response:

You could try:

as.Date(c(rbind(dates - 1, dates)), origin = "1970-01-01")
#>  [1] "1990-02-07" "1990-02-08" "1990-03-27" "1990-03-28" "1990-05-15"
#>  [6] "1990-05-16" "1990-07-04" "1990-07-05" "1990-07-12" "1990-07-13"
#> [11] "1990-08-21" "1990-08-22" "1990-10-02" "1990-10-03" "1990-10-28"
#> [16] "1990-10-29" "1990-11-13" "1990-11-14" "1990-12-06" "1990-12-07"
#> [21] "1990-12-17" "1990-12-18" "1991-01-07" "1991-01-08" "1991-01-31"
#> [26] "1991-02-01" "1991-02-06" "1991-02-07"

Data

dates <- c("1990-02-08", "1990-03-28", "1990-05-16", "1990-07-05", "1990-07-13", 
"1990-08-22", "1990-10-03", "1990-10-29", "1990-11-14", "1990-12-07", 
"1990-12-18", "1991-01-08", "1991-02-01", "1991-02-07")

dates <- as.Date(dates)

Created on 2021-11-04 by the reprex package (v2.0.0)

  • Related