I have a data frame :
dt <- read.table(text = "
350 16
366 11
376 0
380 0
397 0
398 45
400 19
402 0
510 0
525 0
537 0
549 0
569 112
578 99")
I want to delete all rows with a zero in the second column except the row before and after a non zero value.
The result will be :
dt1 <- read.table(text = "
350 16
366 11
376 0
397 0
398 45
400 19
402 0
549 0
569 112
578 99")
library(data.table)
setDT(dt)
dt[{n0 <- V2 != 0; n0 | shift(n0) | shift(n0, type = 'lead')}]
#or
dt[(n0 <- V2 != 0) | shift(n0) | shift(n0, type = 'lead')] # thanks @Frank
# V1 V2
# 1: 350 16
# 2: 366 11
# 3: 376 0
# 4: 397 0
# 5: 398 45
# 6: 400 19
# 7: 402 0
# 8: 549 0
# 9: 569 112
# 10: 578 99
Edit:
Now that data.table::shift
accepts vectors with some negative and some positive elements you can use the code below instead
dt[Reduce('|', shift(V2 != 0, -1:1))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With