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
- x: It is an input dataset / dataframe.
- 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.
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
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
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
Example 3: Get the 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
Example: 5: Usage 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.
rv <- 1:21
mtrx <- matrix(rv, nrow = 7, ncol = 3)
cat("Using head() function to get first 4 rows", "\n")
head(mtrx, 4)
Output
I hope all these figures and programming will help you!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.