Check if Column Exists in Data Frame in R (Example)
In this R tutorial you’ll learn how to inspect whether a variable exists in a data frame.
Table of contents:
Sound good? Let’s jump right to the examples:
Example Data
In the example of this R tutorial, we’ll use the following data frame as basement:
data <- data.frame(col1 = 1:5, # Create example data col2 = letters[1:5], col3 = 3) data # Inspect example data # col1 col2 col3 # 1 1 a 3 # 2 2 b 3 # 3 3 c 3 # 4 4 d 3 # 5 5 e 3
Our example data contains five rows and three columns. The variables are called col1, col2, and col3.
Example: Search for Column Name in Data Frame
If we want to find a variable in a data frame, we can use a combination of the %in%-operator and the colnames function:
"col3" %in% colnames(data) # Check if column exists # TRUE
As you can see, the previous R code returned the logical value TRUE to the RStudio console. This means that the column name “col3” exists in our data frame.
Let’s check another column name:
"other_col" %in% colnames(data) # Column does not exist # FALSE
The RStudio console returns FALSE, i.e. the variable “other_col” is not existing in our data matrix.
Video, Further Resources & Summary
I have recently published a video on the Statistics Globe YouTube channel, which explains the content 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.
Furthermore, you might want to have a look at some of the other tutorials of my website. You can find a selection of other tutorials below.
Summary: At this point you should have learned how to look for certain column names in a data matrix in the R programming language. If you have any additional comments and/or questions, let me know in the comments section.
Statistics Globe Newsletter