What is head() Function in R

The head() function in R is “used to display the first n rows in the input data frame”.

Syntax

head(x, n = number)

Parameters

  1. x: It is an input dataset / dataframe.
  2. n: It is the number of rows that the function should display.

Return value

The head() function returns an object like the input object.

Example 1: The head() function with data frame

Let’s get the first three rows of the data frame using the head() function.

df <- data.frame(c1 = c("a", "b", "c", "d"),
                 c2 = c("e", "f", "g", "h"),
                 c3 = c("i", "j", "k", "l"),
                 c4 = c("m", "n", "o", "p"),
                 c5 = c("q", "r", "s", "t"))

df
cat("First three rows of data frame", "\n")
head(df, 3)

Output

   c1 c2 c3 c4 c5
1  a  e  i  m  q
2  b  f  j  n  r
3  c  g  k  o  s
4  d  h  l  p  t
First three rows of data frame
   c1 c2 c3 c4 c5
1  a  e  i  m  q
2  b  f  j  n  r
3  c  g  k  o  s

Example 2: The head() function with vector

Applying the head() function to a Vector will return the number of elements equal to the n parameter of the head() function.

rv <- 1:10
rv
cat("First five integers of vector", "\n")
head(rv, 5)

Output

[1] 1 2 3 4 5 6 7 8 9 10
First five integers of vector
[1] 1 2 3 4 5

Example 3: The head() function with matrix

Let’s create a matrix of 5 X 3 and fetch the first 3 rows of the Matrix using the head() function.

rv <- 1:15
mtrx <- matrix(rv, nrow = 5, ncol = 3)
mtrx
cat("Using head() function to get first 3 rows", "\n")
head(mtrx, 3)

Output

     [,1] [,2] [,3]
[1,]  1    6    11
[2,]  2    7    12
[3,]  3    8    13
[4,]  4    9    14
[5,]  5   10    15
Using head() function to get first 3 rows
     [,1] [,2] [,3]
[1,]  1    6    11
[2,]  2    7    12
[3,]  3    8    13

Example 4: The head() function with dataset

We will import the USArrests inbuilt R dataset and use that dataset’s head() function.

df <- datasets::USArrests

Use the head() function to get the first five rows of the dataset.

df <- datasets::USArrests
head(df, 5)

Output

           Murder Assault UrbanPop  Rape
Alabama    13.2    236     58       21.2
Alaska     10.0    263     48       44.5
Arizona    8.1     294     80       31.0
Arkansas   8.8     190     50       19.5
California 9.0     276     91       40.6

That’s it.

Leave a Comment