在 R 向量中插入以前的日期

Inserting Previous Dates in R Vector

我正在尝试在 R 的向量中插入每个日期的前一个日期。 这是我当前的向量:

[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"

我正在尝试获取以下内容:

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

等等

我尝试了以下方法:

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

但是,使用这种方法,某些日期不会滞后。 有更好的方法吗?

编辑:回答评论,这是我的代码(用其起始值替换 CSV):

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)

由于某些原因,例如“1990-10-29”之前没有“1990-10-28”,我不明白为什么。

你可以试试:

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"

数据

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)

reprex package (v2.0.0)

于 2021-11-04 创建