head() in R to view the first elements

head() function in R is one of the most useful functions that lets you quickly get a peek at the data you have in a R object. Using head() function in R, you can view the first elements in a vector, matrix, dataframe and other R objects. In this tutorial, we will use head() function to see the first elements in a vector, matrix, and dataframe with multiple examples.

View the first few elements in a vector using head() in R

First, let us use head() function to take a look at the top elements in a vector. We use seq() function to create a vector containing sequence of numbers.

my_vector <- seq(1000)

When we use head() function on the vector, it prints the first 6 elements in the vector by default.

head(my_vector)

## [1] 1 2 3 4 5 6

By using the argument n to the head function, we can specify the number of elements in the vector to print. In this example we use n=10 to see the first 10 elements in the vector.

head(my_vector, n = 10)
##  [1]  1  2  3  4  5  6  7  8  9 10

See the first few elements in a matrix using head() in R

We can also use head() function to get a look at the first few rows of a matrix. Let us create a matrix using matrix() function.

my_matrix <- matrix(seq(1000), ncol=5)

By default, head() function prints the first 6 rows.

head(my_matrix)
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1  201  401  601  801
## [2,]    2  202  402  602  802
## [3,]    3  203  403  603  803
## [4,]    4  204  404  604  804
## [5,]    5  205  405  605  805
## [6,]    6  206  406  606  806

We can provide the number of rows we want to print as argument to head() function. In this example, we have provided n=3 to see the first 3 rows.

head(my_matrix, 3)
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1  201  401  601  801
## [2,]    2  202  402  602  802
## [3,]    3  203  403  603  803

Get a peek at the top elements in a dataframe using head() in R

head() function also works with dataframes. By default, head() function applied to a dataframe shows the first 6 rows of the dataframe.

head(ChickWeight)
##   weight Time Chick Diet
## 1     42    0     1    1
## 2     51    2     1    1
## 3     59    4     1    1
## 4     64    6     1    1
## 5     76    8     1    1
## 6     93   10     1    1

With n argument to head() function, we can specify the number of rows to print. In this example, we ask head() function to print the first 3 rows of the dataframe.

head(ChickWeight, n=3)

##   weight Time Chick Diet
## 1     42    0     1    1
## 2     51    2     1    1
## 3     59    4     1    1

Here we look at the first 10 rows of the dataframe.

head(ChickWeight, n=10)

##    weight Time Chick Diet
## 1      42    0     1    1
## 2      51    2     1    1
## 3      59    4     1    1
## 4      64    6     1    1
## 5      76    8     1    1
## 6      93   10     1    1
## 7     106   12     1    1
## 8     125   14     1    1
## 9     149   16     1    1
## 10    171   18     1    1
Exit mobile version