head()
head(x, n = 6L, ...) head() returns the first n rows of a vector, matrix, data frame, or function. It is the complement of tail(), which returns the last n elements. This function is essential for quickly inspecting large datasets without loading the entire object into memory.
Syntax
head(x, n = 6L, ...)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | object | required | A vector, matrix, data frame, or function |
n | integer | 6L | Number of elements/rows to return |
... | arguments | none | Additional arguments passed to or from other methods |
Examples
Basic usage with a vector
x <- 1:20
head(x)
# [1] 1 2 3 4 5 6
head(x, n = 3)
# [1] 1 2 3
The default n = 6 shows six elements, which is usually enough to verify structure without flooding the console. Specifying n explicitly gives you control over how much data you see: use a small number during interactive exploration to keep output compact, and a larger number when you need to inspect more rows before deciding on the next transformation step.
Working with a data frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Grace"),
score = c(95, 87, 92, 78, 88, 91, 85)
)
head(df)
# name score
# 1 Alice 95
# 2 Bob 87
# 3 Charlie 92
# 4 Diana 78
# 5 Eve 88
# 6 Frank 91
When you call head() on a data frame, the result is itself a data frame with the same column structure as the original. Row names are preserved, and all columns are shown regardless of width. This makes head() the go-to sanity check after reading in a dataset: one glance confirms that the column names, types, and first few values match what you expected from the data source description.
Using head() with negative n
# Return all but the last n elements
head(x, n = -2)
# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
A negative n argument tells head() to exclude the last |n| elements rather than return the first n. This is equivalent to x[1:(length(x) + n)] when n is negative, but the head() version reads more naturally. Use this pattern when you know you want to drop a fixed number of trailing observations, such as removing the last two rows of a time series that contain incomplete data or footnotes.
Common patterns
Quick data inspection workflow
# Standard exploratory workflow
head(df) # View first rows
tail(df) # View last rows
str(df) # View structure
dim(df) # View dimensions
The four-function sequence head(), tail(), str(), and dim() is a well-established exploratory pattern that many R users run automatically after loading any new dataset. Each function answers a distinct question: what does the top look like, what does the bottom look like, what are the column types, and how big is the table. Together they provide a complete structural overview in four lines.
Pipe-friendly usage
library(dplyr)
df %>%
head(10) %>%
summary()
Placing head() inside a dplyr pipeline limits the number of rows that downstream operations process and display. This is particularly valuable during interactive development when you are iterating on a complex sequence of filters, mutations, and joins: adding head(10) near the end lets you see representative output instantly instead of waiting for the full dataset to render, then removing it when the logic is correct.
Previewing imported data
# After reading a large CSV, quickly check the first few rows
data <- read.csv("large_file.csv")
head(data)
head() in practice
head() returns the first n elements of a vector, or the first n rows of a data frame or matrix. The default is n = 6. Negative n values omit the last abs(n) elements: head(x, -2) returns all but the last two elements. This negative-index behavior makes head() useful for removing a trailing element without knowing the total length.
For data frames, head() is the standard way to inspect a newly loaded dataset: head(df) shows the first 6 rows with all columns. For wide data frames where columns wrap, tibble::glimpse() gives a more compact view that fits each column on one line. For the last rows, tail() works identically but from the end.
head() is also useful in pipelines to limit output during development: big_dataset |> filter(...) |> head(20) previews the first 20 rows of a filtered result without loading all results. In production code, slice_head(n = 20) from dplyr is more explicit about operating on rows.
For efficient peeking at large files before reading them into memory, readLines(file, n = 10) reads the first 10 lines directly from disk. head() on the other hand operates on data already in memory, so it does not reduce read overhead, just display overhead.
head() returns the first n elements or rows (default 6). Negative n returns all but the last |n| elements, head(x, -2) drops the last two. For data frames, it returns the first n rows with all columns. The complementary function tail() returns the last n rows. In tidyverse pipelines, slice_head(n = 6) is equivalent and pipe-friendly.
head() returns the first n rows or elements (default 6). For data frames, it preserves all columns and returns the first n rows as a data frame. For vectors, it returns the first n elements.
Negative n is supported: head(x, -2) returns all but the last two elements, equivalent to x[seq_len(length(x) - 2)] but more readable. This is the base R way to drop the last N observations without knowing the total length.
tail() is the complementary function, returning the last n rows or elements. tail(x, -2) drops the first two elements.
In tidyverse pipelines, slice_head(n = 5) is more pipe-friendly than head() because it operates as a dplyr verb and respects group_by(), when grouped, it returns the first 5 rows from each group rather than the first 5 rows overall.
head() does not copy data for data frames in modern R — it uses an integer subset, so peeking at a large data frame with head() is fast and memory-efficient.
Using head() on matrices with row names
Matrices with named rows carry the row labels through head(), so the output remains self-documenting:
m <- matrix(rnorm(50), nrow = 10, ncol = 5)
rownames(m) <- paste0("obs_", 1:10)
colnames(m) <- paste0("var_", 1:5)
head(m, n = 4)
# var_1 var_2 var_3 var_4 var_5
# obs_1 -0.56047565 1.2240818 -1.06782371 0.4264642 -0.6947070
# obs_2 -0.23017749 0.3598138 -0.21797491 -0.2950715 -0.2079173
# obs_3 1.55870831 0.4007715 -1.02600445 0.8951257 -1.2653964
# obs_4 0.07050839 0.1106827 -0.72889123 0.8781335 2.1689560
The row labels make it immediately clear which observations appear first in the dataset. When you are working with time-indexed matrices or patient-labelled clinical data, this named-row behavior lets head() serve as a quick status check without needing to cross-reference row indices against a separate key.
Capturing head() output for documentation
# Save the first 3 rows as a string for README or doc examples
capture.output(head(mtcars, n = 3))
# [1] " mpg cyl disp hp drat wt qsec vs am gear carb"
# [2] "Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4"
# [3] "Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4"
# [4] "Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1"
capture.output() redirects the console representation of head() into a character vector that you can paste into documentation, vignettes, or issue reports. This avoids the awkward workflow of running the code, copying from the console, and manually trimming the output — the captured string is already trimmed to exactly the rows you requested.