Search code examples
rfilterdplyr

How to get the "head" and "tail" of a tibble at the same time


I want to filter the first 5 rows and the last 5 rows at the same time, preferably using dplyr because I'm trying to get used to pipes %>& and I need a tibble with 5 first and 5 last. I can do it but separately.

For first 5:

cars %>% 
  filter(row_number() >= (n() - 4)) 

for last 5:

cars %>% 
  filter( row_number () <=5)

I have also try with slice_head and slice_tail, but I haven't been able to do it with both conditions at the same time.

Alternatively, I did it with base functions, storing each result separately and then putting it together with rbind , but it's less practical.


Solution

  • You can do it with slice :

    library(dplyr)
    mtcars %>% slice(1:5, (n()-4):n())
    
    #                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
    #Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
    #Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
    #Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
    #Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
    #Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
    #Lotus Europa      30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
    #Ford Pantera L    15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
    #Ferrari Dino      19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
    #Maserati Bora     15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
    #Volvo 142E        21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
    

    Similarly, in base R you can do :

    n <- nrow(mtcars)
    mtcars[c(1:5, (n-4):n), ]