R中使用滞后函数调用多个值

Use lag function in R to call multiple values

我提出了一个类似的问题: 我收到了一个非常有用的答案。

现在我尝试调用多行而不是上一个主题中的 1 个值。

示例数据:

    md2 <- structure(list(Hdwy = c(45.01, 45.03, 449, 44.46, 43.63, 425, 
41.36, 40.53, 40.1, 39.97, 39.98, 40, 40, 40, 40, 41.36, 40.53, 
40.1, 40, 40), L_ID = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 1)), class = "data.frame", row.names = c(NA, 
-20L))

我用过:

library(dplyr)
spc <- md2 %>%
         mutate(Lag = lag(Hdwy, (1:6)) %>%
         filter(L_ID==1) %>%
         pull(Lag)
spc

期待看到:

> spc 44.46, 43.63, 425, 
>     41.36, 40.53, 40.1

但是我得到错误:

Error: Problem with mutate() input Lag. x n must be a nonnegative integer scalar, not an integer vector of length 200. i Input Lag is `lag(Hdwy, (1:6))

有什么想法吗?我应该改用其他功能吗?

lag只能接受1个号码,您可以尝试滚动操作。

library(dplyr)

md2 %>% 
  mutate(Lag = lead(zoo::rollapply(L_ID == 1, 6, any, fill = NA, align = 'left'))) %>%
  filter(Lag) %>%
  pull(Hdwy)

#[1]  44.46  43.63 425.00  41.36  40.53  40.10  40.00

我确实得到了与最后一个 1 相对应的另一个值 40。

如果您想从每个 1 中获取所有 6 个值,您可以尝试这个基本 R 选项。

inds <- which(md2$L_ID == 1)
md2$Hdwy[unique(sort(c(sapply(inds, `-`, 1:6))))]