如何按条件删除R中的前导行和尾随行?
问题描述:
存在一个带有前行和后行的数据集,这些行的特征值为零.如何以一种优雅的方式删除这样的行?
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))
谢谢.
答
一个选项是
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