R head() Function

R head() function is used to view the first n parts of the vector, matrix, table, or 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

It returns an object like the input object.

Example 1: Viewing the first six rows of data frame

By default, the head() function returns the first six rows of a data frame.

Figure of working of head() function in R

Let’s implement the above figure in R code.

# Create a data frame.
df <- data.frame(
  col1 = c(1, 2, 3, 4, 5, 6, 7),
  col2 = c(8, 9, 10, 11, 12, 13, 14),
  col3 = c(15, 16, 17, 18, 19, 20, 21)
)

# Applying head() function to df
head(df)

Output

Output of head() function on default behaviour

We can verify from the output that the head() function returns the first six rows of a data frame.

Example 2: Selecting the first n rows from a data frame

Figure of Selecting the first 3 rows from a data frame

Let’s implement the figure into the R code.

# Create a data frame.
df <- data.frame(
  col1 = c(1, 2, 3, 4, 5, 6, 7),
  col2 = c(8, 9, 10, 11, 12, 13, 14),
  col3 = c(15, 16, 17, 18, 19, 20, 21)
)

# Selecting first 3 rows
head(df, 3)

Output

Selecting first three rows of data frame using head() function

Example 3: Get the first n values in the specific column

Figure of using head() function to get first n values in the specific column

Let’s implement the above figure in R code.

# Create a data frame.
df <- data.frame(
  col1 = c(1, 2, 3, 4, 5, 6, 7),
  col2 = c(8, 9, 10, 11, 12, 13, 14),
  col3 = c(15, 16, 17, 18, 19, 20, 21)
)

# Selecting first 4 rows of column 3
head(df$col2, 4)

Output

[1] 8 9 10 11

Example 4: Usage with dataset

df <- datasets::USArrests

head(df, 5)

Output

Using head() function with dataset

Example: 5: Usage with vector

Using head() function with vector

rv <- 1:5

cat("First three values of vector", "\n")

head(rv, 3)

Output

[1] 1 2 3

Example 6: Usage with matrix

Let’s create a matrix of 7×3 and fetch the first four rows of the Matrix.

Figure of using head() function with matrix

rv <- 1:21

mtrx <- matrix(rv, nrow = 7, ncol = 3)

cat("Using head() function to get first 4 rows", "\n")

head(mtrx, 4)

Output

Using head() function with matrix

I hope all these figures and programming will help you!

Leave a Comment