In R, how to retrieve 'second to last' data of every group



I want to retrieve ‘second to last’ data of every group . Currently ,the code as below, using ‘group_modify’ twice. Is there any available function for this? (how to simply current code)? Thanks!

The wished result in the red rectangular in attached image.

test_data <- data.frame(category=c("a","a","c","a","b","c","a","b","c"),

test_data %>%  arrange(category ) %>% 
  group_by(category) %>% 
group_modify(~tail(.x,2)) %>% 

enter image description here


We could use nth(value, -2), which gives second last of each group:


  test_data %>%  
    arrange(category ) %>% 
    group_by(category) %>% 
    summarise(value1 = nth(value, -2))
  category value1
  <chr>     <dbl>
1 a          1.29
2 b         -0.49
3 c          0.61

Answered By – TarJae

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More