0

Is there a function in BASE R that could show the first and last rows within in a data frame? I know the functions like ropls::strF and print an object in data.table could do this. It is not like this topic Select first and last row from grouped data

  ropls::strF(iris)
  #Sepal.Length Sepal.Width ... Petal.Width Species
  #numeric     numeric ...     numeric  factor
  #nRow nCol size NAs
  #150    5 0 Mb   0
  #Sepal.Length Sepal.Width ... Petal.Width   Species
#1            5.1         3.5 ...         0.2    setosa
#2            4.9           3 ...         0.2    setosa
#...          ...         ... ...         ...       ...
#149          6.2         3.4 ...         2.3 virginica
#150          5.9           3 ...         1.8 virginica

library(data.table)
a <- as.data.table(iris)
a
 # Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
 #1:          5.1         3.5          1.4         0.2    setosa
 #2:          4.9         3.0          1.4         0.2    setosa
 #3:          4.7         3.2          1.3         0.2    setosa
 #4:          4.6         3.1          1.5         0.2    setosa
 #5:          5.0         3.6          1.4         0.2    setosa
 #---                                                            
 #146:          6.7         3.0          5.2         2.3 virginica
 #147:          6.3         2.5          5.0         1.9 virginica
 #148:          6.5         3.0          5.2         2.0 virginica
 #149:          6.2         3.4          5.4         2.3 virginica
 #150:          5.9         3.0          5.1         1.8 virginica
Minyi Han
  • 807
  • 1
  • 8
  • 15

1 Answers1

0

As others said in the comments, there isn't a function in base R to do this, but it's straightforward enough to write a function that binds together the first N rows and last N rows.

head_and_tail <- function(x, n = 1) {
  rbind(
    head(x, n),
    tail(x, n)
  )
}

head_and_tail(iris, n = 3)
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1            5.1         3.5          1.4         0.2    setosa
#> 2            4.9         3.0          1.4         0.2    setosa
#> 3            4.7         3.2          1.3         0.2    setosa
#> 148          6.5         3.0          5.2         2.0 virginica
#> 149          6.2         3.4          5.4         2.3 virginica
#> 150          5.9         3.0          5.1         1.8 virginica

Created on 2018-12-22 by the reprex package (v0.2.1)

camille
  • 16,432
  • 18
  • 38
  • 60