Select Data Frame Column Using Character Vector in R (Example)

 

In this R programming tutorial you’ll learn how to extract a data frame variable based on a character string.

Table of contents:

Let’s just jump right in…

 

Creating Example Data

First, let’s create some example data:

data <- data.frame(x1 = 1:5,           # Creating example data
                   x2 = letters[1:5],
                   x3 = 7)
data                                   # Printing example data
#   x1 x2 x3
# 1  1  a  7
# 2  2  b  7
# 3  3  c  7
# 4  4  d  7
# 5  5  e  7

Our data frame contains five rows and three variables.

Let’s also use the colnames function to create a data object containing the column names of our data frame:

data_cols <- colnames(data)            # Storing column names
data_cols                              # Printing column names
# "x1" "x2" "x3"

 

Example: Select Column with [] Instead of $-Operator

Typically, we would use the $-operator to select certain variables from our data frame. However, if we want to extract variables dynamically based on a character string this is not possible. Let’s give it a try:

data$data_cols[1]                      # Trying to use $-operator
# NULL

As you can see, the previous R code is returning NULL.

Fortunately, we can use square brackets instead. Have a look at the following R code:

data[ , data_cols[1]]                  # Subset using square brackets
# 1 2 3 4 5

As you can see, the previous syntax returned the values of our first variable x1 (i.e. the first element in data_cols). For instance, subsetting variables with square brackets instead of the $-operator can be very useful in for-loops, while-loops, or user-defined functions.

 

Video, Further Resources & Summary

Do you need further info on the R codes of this tutorial? Then you may watch the following video of my YouTube channel. In the video, I’m explaining the topics of this tutorial in a live session.

 

 

Additionally, you might want to read the other articles of my website. I have released several posts about the extraction of variables from data frames already.

 

Summary: In this tutorial you learned how to access the elements of a variable using a character string in R programming. Let me know in the comments section, in case you have further 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