Nancy
Nancy

Reputation: 21

How to select the last five rows in a table by using function slice()?

I want to select the last five rows of a dataset called dat by using function slice(). I tried slice(dat, 5L) but it only returned one row. What else can I try?

Upvotes: 1

Views: 953

Answers (3)

thothal
thothal

Reputation: 20329

This should do the trick

library(dplyr)
mtcars %>% slice((n()-4):n())

Upvotes: 2

slava-kohut
slava-kohut

Reputation: 4233

FIY, slice silently drops row names:

mtcars %>% slice((n()-4):n())

If you want to avoid this, simply use tail:

tail(mtcars, 5)

Upvotes: 2

akrun
akrun

Reputation: 887098

slice needs a vector of index to return that many rows. According to ?slice

... - Integer row values. Provide either positive values to keep, or negative values to drop. The values provided must be either all positive or all negative. Indices beyond the number of rows in the input are silently ignored.

. Here, we can pass the row_number() with tail to get the last 5 row_numbers

library(dplyr) 
df1 %>%
    slice(tail(row_number(), 5))

Upvotes: 3

Related Questions