Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows with zero value under condition

Tags:

dataframe

r

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")
like image 547
Noura Avatar asked Dec 11 '22 05:12

Noura


1 Answers

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))]
like image 125
IceCreamToucan Avatar answered Jan 07 '23 21:01

IceCreamToucan