head, tail

Obtain the first several rows of a matrix or data frame using head, and use tail to obtain the last several rows. These functions may also be applied to obtain the first or last values in a vector.
head(x, n=6)
  • x – A matrix, data frame, or vector.
  • n – The first n rows (or values if x is a vector) will be returned.
tail(x, n=6)
  • x – A matrix, data frame, or vector.
  • n – The last n rows (or values if x is a vector) will be returned.

Example. Below are four examples of use of head and tail.
> library(MASS)
> data(Boston)
> head(Boston, 3)
     crim zn indus chas   nox    rm  age    dis rad tax
1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296
2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242
3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242
  ptratio  black lstat medv
1    15.3 396.90  4.98 24.0
2    17.8 396.90  9.14 21.6
3    17.8 392.83  4.03 34.7
> 
> tail(Boston)
       crim zn indus chas   nox    rm  age    dis rad tax
501 0.22438  0  9.69    0 0.585 6.027 79.7 2.4982   6 391
502 0.06263  0 11.93    0 0.573 6.593 69.1 2.4786   1 273
503 0.04527  0 11.93    0 0.573 6.120 76.7 2.2875   1 273
504 0.06076  0 11.93    0 0.573 6.976 91.0 2.1675   1 273
505 0.10959  0 11.93    0 0.573 6.794 89.3 2.3889   1 273
506 0.04741  0 11.93    0 0.573 6.030 80.8 2.5050   1 273
    ptratio  black lstat medv
501    19.2 396.90 14.33 16.8
502    21.0 391.99  9.67 22.4
503    21.0 396.90  9.08 20.6
504    21.0 396.90  5.64 23.9
505    21.0 393.45  6.48 22.0
506    21.0 396.90  7.88 11.9
> 
> head(1:50, 10)
 [1]  1  2  3  4  5  6  7  8  9 10
> 
> tail(1:50, 1)
[1] 50

Leave a Reply