What is the head() function in R?
Overview
The head() function in R is used to determine the first or last part of an R object.
Syntax
head(x, n)
Parameter value
The head() function takes the following parameter values.
x: This represents the R object (a matrix, data.frame, ftable, table, function).n: This represents a single integer. When given a zero or positive value, the output object contains the number of elements for a given vector, the rows for a given matrix or data frame, or lines for a given function. When given a negative value, all but the first or lastnnumber of elements of the input R object are returned.
Return value
The head() function returns an object like that of the input object, x.
Example
# creating a data frame objectmydataframe<- data.frame(numbers = 1:10,alphabets = LETTERS[1:10],symbol = c('*', '!', '#', '?', ',', '/', '=', '+', '<', ')'))# implementing the head() function returning only 7 rows of the data framehead(mydataframe, n=7)
Explanation
- Lines 2 to 6: We create an R object (a data frame)
mydataframeusing thedata.frame()function. - Line 9: We implement the
head()function by making the resulting data frame have only7rows.