Delete a row in R based on next row condition
You don't need loops for this. You can do it with a single line in base R by combining a grepl
with a lagged grepl
df1[!c(head(grepl(":", df1$a), -1) & tail(grepl(":", df1$a), -1), FALSE),]
#> b a
#> 1 1 value1
#> 2 2 value2
#> 4 4 value2:b
#> 5 5 value3
Here is a dplyr
solution.
library(dplyr)
df1 %>%
mutate(flag = grepl(":", a),
flag = cumsum(flag)*flag,
flag = lead(flag, default = 0)) %>%
filter(flag != 2) %>%
dplyr::select(-flag)
# b a
#1 1 value1
#2 2 value2
#3 4 value2:b
#4 5 value3