I made a similar question : If condition is met, go 6 rows above and select the value in R and I received a very usefyl answer.
Now I am trying to call instead of 1 value as in the previous topic, multiple rows instead.
Sample data:
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))
I used :
library(dplyr)
spc <- md2 %>%
mutate(Lag = lag(Hdwy, (1:6)) %>%
filter(L_ID==1) %>%
pull(Lag)
spc
Expecting to see:
> spc 44.46, 43.63, 425,
> 41.36, 40.53, 40.1
But I get the error:
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))
Any ideas? Should I use a different function instead?