使用r中的条件语句删除组的前3行 [英] removing the first 3 rows of a group with conditional statement in r

查看:50
本文介绍了使用r中的条件语句删除组的前3行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除不满足我想要的条件的行.例如:

I would like to remove rows that are not fulfilling the condition that I want. For example:

Event   Value
  1       1
  1       0
  1       0
  1       0
  2       8
  2       7
  2       1
  2       0
  2       0
  2       0
  3       8
  3       0
  3       0
  3       0
  3       0

如果每个事件的值列中都有一个大于2的数字(值> 2),请从该值开始的前3行中删除不符合条件的行.
它应该看起来像这样:

If per event, in the column of value there is a number higher than 2 (Value > 2) remove the first 3 rows starting from that Value that is not fulfilling the criteria.
It should look like this:

Event   Value
  1       1
  1       0
  1       0
  1       0
  2       0
  2       0
  3       0
  3       0

我已经能够删除满足条件的每个事件的第一行,但是还没有找到删除其他行的方法.

I have been able to remove the first row of each Event that accomplish the criteria, but haven't find a way to remove the other rows.

Event<- c(1,1,1,1,2,2,2,2,2,2,3,3,3,3,3)  
Value<- c(1,0,0,0,8,7,1,0,0,0,8,0,0,0,0)
A<- data.frame(Event, Value)

  A %>%
  group_by(Event) %>%
  filter(!(Value >= 2 & row_number() == 1))

有什么主意吗?

推荐答案

此处是 slice 的一个选项.按事件"分组后,检查是否是否有 any 'Value'大于或等于2,然后从该序列的第一个匹配项返回该序列的负索引case或 else 返回 row_number().负索引会删除这些行

Here is an option with slice. After grouping by 'Event', check if there are any 'Value' greater than or equal to 2, then return the negative index of the sequence from the first occurrence of that case or else return the row_number(). The negative index removes those rows

library(dplyr)
A %>% 
     group_by(Event) %>% 
     slice(if(any(Value >=2)) -(which(Value >=2)[1] + 0:2) else row_number())

这篇关于使用r中的条件语句删除组的前3行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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