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?
This should do the trick
library(dplyr)
mtcars %>% slice((n()-4):n())
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))
FIY, slice
silently drops row names:
mtcars %>% slice((n()-4):n())
If you want to avoid this, simply use tail
:
tail(mtcars, 5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.