0

I need to get the last row of each group in a dataframe grouped by two columns.

I've tried some options seen in other posts but they're nor working for me.

This is my dataframe:

   Day        Date                  Status    Element
 1 2020-09-01 2020-09-01 07:00:00        0          A
 2 2020-09-01 2020-09-01 07:00:00        0          B
 3 2020-09-01 2020-09-01 07:00:00        1          C
 4 2020-09-01 2020-09-01 07:00:00        1          D
 5 2020-09-01 2020-09-01 08:00:00        0          E

It is grouped by Day and Element. I need the last row of each group when the column Status is 1.

I'm trying this:

output = df%>% 
      filter(status== 1) %>% 
      slice(n())

But I'm getting the error: Error in UseMethod("slice") : no applicable method for 'slice' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"

MustardRecord
  • 305
  • 4
  • 14

2 Answers2

2

Package dplyr has a nice function for doing this.

library(tidyverse)

iris %>% 
    group_by(Species) %>% 
    slice_tail(n = 1)
Celso Silva
  • 136
  • 5
0

This is actually working:

output = df %>% 
      filter(Status == 1) %>% 
      do(tail(., 1))
MustardRecord
  • 305
  • 4
  • 14