如何在 r 中获取 7 天或 10 天旧值的数据?

How to get data for 7 day or 10 day old value in r?

我正在尝试从数据中查找 7 天前的值,但无法使用 dplyr 或 base R 对该值进行子集化。

library(nycflights13)
library(tidyverse)
library(lubridate)


nycflights13::flights %>% 
  mutate(date = ymd(paste(year,"-",month,"-",day))) %>% 
  dplyr::select(date, carrier, flight, origin, dest, arr_delay) %>% 

  group_by(carrier, flight, origin, dest) %>% 
  arrange(desc(date)) %>% 

  mutate(old_delay = .[.$date - 7, "arr_delay"])
  # mutate(old_delay = . %>% filter(date - 7) %>% select(arr_delay))



# ERROR
Error: Problem with `mutate()` column `old_delay`.
i `old_delay = .[.$date - 7, "arr_delay"]`.
x Must subset rows with a valid subscript vector.
x Subscript `i` has the wrong type `date`.
i It must be logical, numeric, or character.
i The error occurred in group 1: carrier = "9E", flight = 2900, origin = "JFK", dest = "BNA".

如何将旧值提取到新列中。我需要在 mutate 中使用 apply 吗?

我还查看了 zoo 包,其中使用了时间 windows 但找不到提取确切值的函数。

期望的结果: nycflights 可能不是适合此目的的数据集。但是把它看作是一些股票数据集,我试图在其中找到 7 天前的股票收盘价,这样我就可以计算从每天到 7 天旧值的百分比变化。

您在寻找 dplyr::lag 吗?

library(dplyr);library(lubridate)
nycflights13::flights %>% 
  mutate(date=ymd(paste(year, "-", month, "-", day))) %>% 
  dplyr::select(date, carrier, flight, origin, dest, arr_delay) %>% 
  group_by(carrier, flight, origin, dest) %>% 
  mutate(old_delay=dplyr::lag(arr_delay, 7)) %>% 
  arrange(desc(date))