简体   繁体   English

删除包含值的行后面的所有行

[英]Remove all rows following a row that contains a value

I'm attempting to remove all rows that come after a value (or values) but am running into some trouble.我正在尝试删除一个值(或多个值)之后的所有行,但遇到了一些麻烦。

I want to do the opposite of this: Filter to remove all rows before the first time a particular value in a specific column appears我想做与此相反的操作: 过滤以在特定列中的特定值第一次出现之前删除所有行

Using the example dataframe from the above question:使用上述问题中的示例 dataframe :

(dat<-data.frame(a= c("pete", "mike", "bob", "bart", "bob"), b=c(1,2,3,4,5), c=c("home", "away", "home", "away", "gone")))

         a b    c
    1 pete 1 home
    2 mike 2 away
    3  bob 3 home
    4 bart 4 away
    5  bob 5 gone

I want my result to look like this:我希望我的结果看起来像这样:

     a b    c
1 pete 1 home
2 mike 2 away
3  bob 3 home

Here is what I've tried so far:这是我迄今为止尝试过的:

dat %>% slice(which.min(a == "bob") : n())

But unlike which.max which removed everything before bob this doesn't remove anything after it.但与which.maxbob之前删除所有内容不同,这不会删除之后的任何内容。

We can use我们可以用

library(dplyr)
dat %>% 
     slice(seq(which.max(a == 'bob')))

Or with cumsum或与cumsum

dat %>% 
    filter(lag(cumsum(a == 'bob'), default = 0) < 1)

Or in base R或在base R

dat[seq_len(match('bob', dat$a)),]

Using row_number() :使用row_number()

library(dplyr)
dat %>% filter(row_number() <= match('bob', a))

#     a b    c
#1 pete 1 home
#2 mike 2 away
#3  bob 3 home

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM