How delete leading and trailing rows by condition in R?
Asked Answered
E

3

2

There is a data set with leading and trailing rows that have a feature with zero value. How to drop such rows in an elegant way?

# Library
library(tidyverse)

# 1. Input
data.frame(
  id = c(1:10),
  value = c(0, 0, 1, 3, 0, 1, 2, 8, 9, 0))

# 2. Delete leading and trimming rows with 'value = 0'
# ...

# 3. Desired outcome
data.frame(
  id = c(3:9),
  value = c(1, 3, 0, 1, 2, 8, 9))

Thanks.

Eddington answered 4/4, 2019 at 16:16 Comment(0)
T
6

An option would be

library(dplyr)   
df1 %>% 
  filter( cumsum(value) > 0 & rev(cumsum(rev(value)) > 0))
#  id value
#1  3     1
#2  4     3
#3  5     0
#4  6     1
#5  7     2
#6  8     8
#7  9     9
Tjaden answered 4/4, 2019 at 16:25 Comment(0)
T
1

The below can be an easy hack:

df %>%
  mutate(value2 = cumsum(value)) %>%
  filter(value2 != 0) %>%
  filter(!(value2 == max(value2) & value == 0)) %>%
  select(-value2)
  id value
1  3     1
2  4     3
3  5     0
4  6     1
5  7     2
6  8     8
7  9     9
Tinsley answered 4/4, 2019 at 16:29 Comment(0)
R
1

One option is to check if the value equals 0 and rleid(value) is at its minimum or maximum (i.e. you're in the first or last group of values). This will work even if the non-zero values you want to keep are negative.

library(data.table)
setDT(df)

df[!(value == 0 & (rid <- rleid(value)) %in% range(rid))]

#    id value
# 1:  3     1
# 2:  4     3
# 3:  5     0
# 4:  6     1
# 5:  7     2
# 6:  8     8
# 7:  9     9

If you know in advance the first and last values will always be zeros, you can just check the second condition

df[!((rid <- rleid(value)) %in% range(rid))]
Rob answered 4/4, 2019 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.