问题
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.
回答1:
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
回答2:
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
回答3:
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))]
来源:https://stackoverflow.com/questions/55520695/how-delete-leading-and-trailing-rows-by-condition-in-r