Hello,
This is easiest to do with the slice function from dplyr I think. I used the iris dataset and the variable x to make the difference clearer with the n() function from dplyr that's counting the rows. I'm also showing the original rowId just to verify the cuts are correct. This is not needed.
library(dplyr)
x = 10
iris %>% mutate(rowId = 1:n()) %>%
slice(1:x, (n()- x + 1):n())
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species rowId
#> 1 5.1 3.5 1.4 0.2 setosa 1
#> 2 4.9 3.0 1.4 0.2 setosa 2
#> 3 4.7 3.2 1.3 0.2 setosa 3
#> 4 4.6 3.1 1.5 0.2 setosa 4
#> 5 5.0 3.6 1.4 0.2 setosa 5
#> 6 5.4 3.9 1.7 0.4 setosa 6
#> 7 4.6 3.4 1.4 0.3 setosa 7
#> 8 5.0 3.4 1.5 0.2 setosa 8
#> 9 4.4 2.9 1.4 0.2 setosa 9
#> 10 4.9 3.1 1.5 0.1 setosa 10
#> 11 6.7 3.1 5.6 2.4 virginica 141
#> 12 6.9 3.1 5.1 2.3 virginica 142
#> 13 5.8 2.7 5.1 1.9 virginica 143
#> 14 6.8 3.2 5.9 2.3 virginica 144
#> 15 6.7 3.3 5.7 2.5 virginica 145
#> 16 6.7 3.0 5.2 2.3 virginica 146
#> 17 6.3 2.5 5.0 1.9 virginica 147
#> 18 6.5 3.0 5.2 2.0 virginica 148
#> 19 6.2 3.4 5.4 2.3 virginica 149
#> 20 5.9 3.0 5.1 1.8 virginica 150
If you like to use it as a function you can write it like this:
library(dplyr)
sliceEnds = function(myData, x){
if(2 * x < nrow(myData)){
myData %>%
slice(1:x, (n()- x + 1):n())
} else {
myData
}
}
sliceEnds(iris, 10)
Not that here if the slicing set is larger than the data frame, the whole data frame is returned.
Created on 2022-04-23 by the reprex package (v2.0.1)
Hope this helps,
PJ