如何按条件删除R中的前导行和尾随行? [英] How delete leading and trailing rows by condition in R?

查看:52
本文介绍了如何按条件删除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

这篇关于如何按条件删除R中的前导行和尾随行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆