Extract Row from Data Frame in R (2 Examples)
In this tutorial, I’ll illustrate how to return a certain row of a data frame in the R programming language.
The article looks as follows:
- Construction of Example Data
- Example 1: Get One Specific Row of Data Frame
- Example 2: Return Multiple Rows of Data Frame
- Video & Further Resources
Let’s start right away…
Construction of Example Data
We’ll use the following R data frame as example data for the following example.
data <- data.frame(x1 = 1:4, # Create example data x2 = 2:5, x3 = 9) data # Print example data # x1 x2 x3 # 1 1 2 9 # 2 2 3 9 # 3 3 4 9 # 4 4 5 9
As you can see based on the output of the RStudio console, our data consists of four rows and three numeric columns.
Example 1: Get One Specific Row of Data Frame
In case we want to extract a specific row of our example data, we can specify within square brackets the row index of the row we want to return. Consider the following R programming syntax:
data[2, ] # Extract row of data # x1 x2 x3 # 2 2 3 9
As you can see, the RStudio console returned the second row of our data frame.
Note that we had to specify the index of our row in front of a comma, in order to tell the R programming language that we want to extract a row. If we would specify the number 2 after the comma, we would extract a variable instead of a row.
Example 2: Return Multiple Rows of Data Frame
We can also extract multiple rows from a data frame in R. We simply need to specify a vector instead of a single value within the square brackets:
data[c(1, 4), ] # Get multiple rows # x1 x2 x3 # 1 1 2 9 # 4 4 5 9
In this example, we returned the first and the fourth row of our data.
Video & Further Resources
Do you need further info on the R syntax of this tutorial? Then you might have a look at the following video of my YouTube channel. In the video, I’m illustrating the examples of this article in RStudio:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you might read the other articles of my homepage:
- Subset Data Frame Rows by Logical Condition in R
- Sample Random Rows of Data Frame
- Extract Certain Columns of Data Frame
- R Functions List (+ Examples)
- The R Programming Language
At this point you should have learned how to access or subset a row with a particular index in a data matrix in R programming. If you have further questions, tell me about it in the comments below.
Statistics Globe Newsletter