简体   繁体   English

过滤以删除特定列中特定值之前的所有行,而该特定值出现多次

[英]Filter to remove all rows before a particular value in a specific column, while this particular value occurs several time

I would like to filter to remove all rows before a particular value in a specific column.我想过滤以删除特定列中特定值之前的所有行。 For example, in the data frame below, I would like to remove all rows before "1" that appears in column x, for as much as "1" occurs.例如,在下面的数据框中,我想删除 x 列中出现的“1”之前的所有行,因为出现“1”。 Please note that the value of "1" repeats many times and I want to remove the "NA" rows before the "1" in column x, regarding column a.请注意,“1”的值重复了很多次,我想删除 x 列中“1”之前的“NA”行,关于 a 列。 Thanks谢谢

a   b   x
1   1   NA
1   2   NA
1   3   1
1   4   0
1   5   0
1   6   NA
1   7   NA
2   1   NA
2   2   NA
2   3   1
2   4   NA
2   5   0
2   6   0
2   7   NA
3   1   NA
3   2   NA
3   3   NA
3   4   NA
3   5   1
3   6   0
3   7   NA

the desired output would be like this:所需的 output 将是这样的:

a   b   x
1   3   1
1   4   0
1   5   0
1   6   NA
1   7   NA
2   3   1
2   4   NA
2   5   0
2   6   0
2   7   NA
3   5   1
3   6   0
3   7   NA

Does this solve your problem?这能解决你的问题吗?

library(tidyverse)

dat <- read.table(text = "a   b   x
1   1   NA
1   2   NA
1   3   1
1   4   0
1   5   0
1   6   NA
1   7   NA
2   1   NA
2   2   NA
2   3   1
2   4   NA
2   5   0
2   6   0
2   7   NA
3   1   NA
3   2   NA
3   3   NA
3   4   NA
3   5   1
3   6   0
3   7   NA", header = TRUE)

dat %>%
  group_by(a) %>%
  filter(cummax(!is.na(x)) == 1)
#> # A tibble: 13 × 3
#> # Groups:   a [3]
#>        a     b     x
#>    <int> <int> <int>
#>  1     1     3     1
#>  2     1     4     0
#>  3     1     5     0
#>  4     1     6    NA
#>  5     1     7    NA
#>  6     2     3     1
#>  7     2     4    NA
#>  8     2     5     0
#>  9     2     6     0
#> 10     2     7    NA
#> 11     3     5     1
#> 12     3     6     0
#> 13     3     7    NA

Created on 2021-12-07 by the reprex package (v2.0.1)reprex package (v2.0.1) 于 2021 年 12 月 7 日创建

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

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