Extract First N Rows of Data Frame in R (3 Examples)

 

This tutorial illustrates how to subset the first N rows of a data frame in the R programming language.

The tutorial will contain three examples for the extraction of data rows. To be more specific, the post looks as follows:

Let’s start right away!

 

Example Data

In the examples of this R programming tutorial, we’ll use the following data frame as basement:

data <- data.frame(x1 = 1:10,
                   x2 = letters[1:10],
                   x3 = "x")
data
#    x1 x2 x3
# 1   1  a  x
# 2   2  b  x
# 3   3  c  x
# 4   4  d  x
# 5   5  e  x
# 6   6  f  x
# 7   7  g  x
# 8   8  h  x
# 9   9  i  x
# 10 10  j  x

Our example data consists of ten rows and three columns.

In the following, I’ll explain how to select only the first N rows of this data frame in R. So keep on reading!

 

Example 1: Select First 6 Rows with head Function

If we want to extract exactly the first six rows of our data frame, we can use the R head function:

head(data)
#   x1 x2 x3
# 1  1  a  x
# 2  2  b  x
# 3  3  c  x
# 4  4  d  x
# 5  5  e  x
# 6  6  f  x

As you can see based on the output of the RStudio console, the head function returned exactly six rows.

 

Example 2: Select First N Rows with head Function

We can also specify within the head function, how many rows we want to return. Let’s assume that we want to extract the first three rows of our data matrix:

head(data, 3)
#   x1 x2 x3
# 1  1  a  x
# 2  2  b  x
# 3  3  c  x

Looks good! The RStudio console returned three rows.

 

Example 3: Select First N Rows with Square Brackets

Alternatively to the head function, we can also use square brackets to create a subset of our data table. Have a look at the following R code:

data[1:3, ]
# x1 x2 x3
# 1  1  a  x
# 2  2  b  x
# 3  3  c  x

The output is exactly the same as in Example 2, but this time we selected the first three rows with square brackets.

 

Video, Further Resources & Summary

Do you need more information on the R code of this article? Then you might have a look at the following video of the Statistics Globe YouTube channel. I explain the R code of this page in the video.

 

 

Besides that, you might read the other RStudio articles on my homepage. I have published numerous tutorials already:

 

To summarize: In this R article you learned how to choose a specific number of rows to select from the top of a data table. Don’t hesitate to tell me about it in the comments section, if you have additional questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top