Extract Single Element from Data Frame in R (2 Examples)

 

In this tutorial, I’ll show how to access a particular element of a data frame in R.

The content of the article is structured as follows:

So without further ado, let’s do this:

 

Construction of Example Data

We’ll use the following data as basement for this R programming tutorial:

data <- data.frame(x1 = 1:5,    # Creating example data frame
                   x2 = letters[1:5])
data                            # Printing entire example data frame

 

table 1 data frame extract single element from data frame r

 

The previous table shows that our example data consists of five rows and two columns.

 

Example 1: Return Single Element Based On Row Index & Variable Name

In Example 1, I’ll explain how to return only one element from a data matrix using row indices and variable names.

Consider the following R code:

data[3, "x2"]                   # Extract element
# [1] "c"

The RStudio console returns the value “c”, i.e. the third element of the variable x2.

 

Example 2: Return Single Element Based On Row Index & Column Index

In Example 2, I’ll illustrate how to use row and column indices to access a specific element of a data table.

Have a look at the following code:

data[3, 2]                      # Extract element
# [1] "c"

The output is the same as in Example 1. However, this time we have used the column index instead of the variable name.

 

Video, Further Resources & Summary

I have recently published a video on my YouTube channel, which illustrates the topics of this tutorial. You can find the video below.

 

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.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, you might read the related articles on my website:

 

In this tutorial, I have illustrated how to return a certain data frame element in R programming. Please let me know in the comments section, if you have any further comments or questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top