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
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 #  "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 #  "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.
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:
- Extract Subset of Data Frame Rows Containing NA
- Extract Certain Columns of Data Frame
- Extract Row from Data Frame
- Extract Every nth Element of a Vector
- The R Programming Language
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.
Statistics Globe Newsletter