How delete leading and trailing rows by condition in R?

走远了吗. 提交于 2019-12-11 18:03:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!