Search code examples
rif-statementgoto

If condition is met, go 6 rows above and select the value in R


data sample

I am trying to do in R the following: In my dataset (md2, attached), if L_ID=1, go 6 rows above and create a new dataframe with the variable Hway. I use the following command:

spc <- data.frame(md$Hdwy[c(md2$L_ID[-6], 0) == 1])

Expecting to see:

> spc
44.46 40.00

It seems to work, however when I checked I noticed that it selects the value 1 row above instead of 6:

> spc
    40.1 40.00

Any ideas?


Solution

  • How about something like this?

    library(dplyr)
    spc <- md2 %>%
             mutate(Lag = lag(Hdwy, 6L)) %>%
             filter(L_ID==1) %>%
             pull(Lag)
    spc
    [1] 44.46 40.00
    

    Or with base R:

    spc <- md2$Hdwy[which(md2$L_ID == 1) - 6]
    spc
    [1] 44.46 40.00
    

    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))