Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove non-last rows with certain condition per group

Tags:

dataframe

r

dplyr

I have the following dataframe called df (dput below):

  group indicator value
1     A     FALSE     2
2     A     FALSE     1
3     A     FALSE     2
4     A      TRUE     4
5     B     FALSE     5
6     B     FALSE     1
7     B      TRUE     3

I would like to remove the non-last rows with indicator == FALSE per group. This means that in df the rows: 1,2 and 5 should be removed because they are not the last rows with FALSE per group. Here is the desired output:

  group indicator value
1     A     FALSE     2
2     A      TRUE     4
3     B     FALSE     1
4     B      TRUE     3

So I was wondering if anyone knows how to remove non-last rows with certain condition per group in R?


dput of df:

df <- structure(list(group = c("A", "A", "A", "A", "B", "B", "B"), 
    indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE
    ), value = c(2, 1, 2, 4, 5, 1, 3)), class = "data.frame", row.names = c(NA, 
-7L))
like image 386
Quinten Avatar asked Nov 15 '25 15:11

Quinten


1 Answers

Filter using last(which()) to find the row number of the last FALSE row per group:

library(dplyr)

df %>%
  group_by(group) %>%
  filter(indicator | row_number() == last(which(!indicator))) %>%
  ungroup()
# A tibble: 4 × 3
  group indicator value
  <chr> <lgl>     <dbl>
1 A     FALSE         2
2 A     TRUE          4
3 B     FALSE         1
4 B     TRUE          3
like image 166
zephryl Avatar answered Nov 18 '25 05:11

zephryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!