Selecting the top of a data frame

head(___, n = ___)
tail(___, n = ___)
View Interactive Version

Data frames can span a large number of rows and columns. Based on the printed output in the console it can be hard to get an initial impression of the data inside the data frame. This issue is not so much of a problem for tibbles which have a nicer console output. Additionally, it can be helpful to easily retrieve the first rows in one command without any indexing or additional packages.

The TitanicSurvival dataset contains data of 1309 passengers represented as rows. A simple print of the dataset would print all passengers, filling up the entire console. Instead, the head() function shows only the first 10 rows of a data frame including its column names:

Input
head(TitanicSurvival)
Output
                                survived    sex     age
Allen, Miss. Elisabeth Walton        yes female 29.0000
Allison, Master. Hudson Trevor       yes   male  0.9167
Allison, Miss. Helen Loraine          no female  2.0000
Allison, Mr. Hudson Joshua Crei       no   male 30.0000
Allison, Mrs. Hudson J C (Bessi       no female 25.0000
Anderson, Mr. Harry                  yes   male 48.0000
                                passengerClass
Allen, Miss. Elisabeth Walton              1st
Allison, Master. Hudson Trevor             1st
Allison, Miss. Helen Loraine               1st
Allison, Mr. Hudson Joshua Crei            1st
Allison, Mrs. Hudson J C (Bessi            1st
Anderson, Mr. Harry                        1st

The number of columns can be tuned using the parameter n. To extract only the first three rows from the data set you can write:

Input
head(TitanicSurvival, n = 3)
Output
                               survived    sex     age
Allen, Miss. Elisabeth Walton       yes female 29.0000
Allison, Master. Hudson Trevor      yes   male  0.9167
Allison, Miss. Helen Loraine         no female  2.0000
                               passengerClass
Allen, Miss. Elisabeth Walton             1st
Allison, Master. Hudson Trevor            1st
Allison, Miss. Helen Loraine              1st
Select first or last rows of a data frame