Get First N Rows of Data Frame

To get the first N rows of a data frame in R language, call head() function, pass the data frame and the number of rows to fetch, as arguments.

</>
Copy
head(data_frame_name, n=6)

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

To get the first 3 rows of data frame, pass n=3, as second argument to head() function.

</>
Copy
head(data_frame_name, 3)

Examples

Get First N Rows of Data Frame

In the following example, we take a data frame in df, with seven rows, and get the first three n = 3 rows using head() function.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 age = c(4, 8, 10, 14, 18, 10, 12),
                 income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))

result <- head(df, 3)
print(result)

Output

tutorialkart$ Rscript example.r
  name age income
1    A   4    1.6
2    B   8    1.5
3    C  10    1.7

Get First 6 Rows of Data Frame

In the following example, we take a data frame in df, with seven rows, and get the first (default n = 6) rows using head() function.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 age = c(4, 8, 10, 14, 18, 10, 12),
                 income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))

result <- head(df)
print(result)

Output

tutorialkart$ Rscript example.r
  name age income
1    A   4    1.6
2    B   8    1.5
3    C  10    1.7
4    D  14    1.9
5    E  18    1.5
6    F  10    1.0

Conclusion

In this R Tutorial, we learned how to first specific number of rows from a data frame using head() function, with the help of an example programs.