dplyr approach to get the last row number with a positive value

2357 views r
1

library(tidyverse)
df <- tibble(a = c(1, 2, 3, 0, 5, 0, 7, 0, 0, 0)) %>% print()
df[1:max(which(df$a>0)),]

This little code chunk above determines that the 7th row of df is the last row to contain a positive value, and filters every row after this 7th row out of the data frame.

I go from this

# A tibble: 10 x 1
       a
   <dbl>
 1    1.
 2    2.
 3    3.
 4    0.
 5    5.
 6    0.
 7    7.
 8    0.
 9    0.
10    0.

to this

# A tibble: 7 x 1
      a
  <dbl>
1    1.
2    2.
3    3.
4    0.
5    5.
6    0.
7    7.

How can I perform this df[1:max(which(df$a>0)),] using dplyr tidyverse slang? I need to learn base R, and will, but right now I got to do this in the tidyverse.

answered question

1 Answer

13

We can use slice

library(tidyverse)
df %>%
  slice(1:max(which(a > 0)))


#      a
#  <dbl>
#1     1
#2     2
#3     3
#4     0
#5     5
#6     0
#7     7

Or filter

df %>%
  filter(row_number() <= max(which(a > 0)))

posted this

Have an answer?

JD

Please login first before posting an answer.