ltong
ltong

Reputation: 543

How to filter a row and the one after it if a condition is met

I am wondering how I can filter a row and the one after it if a condition is met. For example with the toy dataframe below, I want to filter var2 when it is less than 4 and also the row after that.

df <- data.frame(var1 = c("1635", "1635", "1729", "1729", "1847", "1847"),
                 var2 = c("28", "NA", "2", "NA", "5", "NA"), 
                 )

So the output would look something like this

df <- data.frame(var1 = c("1729", "1729"),
                 var2 = c(2", "NA"), 
                 )

Upvotes: 0

Views: 48

Answers (1)

bretauv
bretauv

Reputation: 8557

df <- data.frame(
  var1 = c(1635, 1635, 1729, 1729, 1847, 1847, 1900, 1901),
  var2 = c(28, NA, 2, NA, 5, NA, 1, 2)
)
df
#>   var1 var2
#> 1 1635   28
#> 2 1635   NA
#> 3 1729    2
#> 4 1729   NA
#> 5 1847    5
#> 6 1847   NA
#> 7 1900    1
#> 8 1901    2

# Find rows that match the condition
to_keep <- which(df$var2 <= 4) 
# Get these rows + those that follow
to_keep <- unique(c(to_keep, to_keep + 1))
to_keep <- sort(to_keep[to_keep <= nrow(df)])

df[to_keep, ]
#>   var1 var2
#> 3 1729    2
#> 4 1729   NA
#> 7 1900    1
#> 8 1901    2

Created on 2022-06-22 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions