← More Guides

Dynamically Select Columns from Variables in R

Video Notes

Let’s walk through how to dynamically select columns from a data frame in R.

First, we’ll set up an example data frame:

df <- data.frame(
  id = 1:5,
  group = c("A", "A", "B", "B", "B"),
  age = c(22, 25, 31, 29, 40),
  height = c(64, 61, 70, 68, 66),
  weight = c(140, 120, 190, 175, 160)
)

If we want to extract the age column, we can simply use the dollar-sign extraction operator:

df$age

This works when we know the column name ahead of time.

When the Column Name Is Dynamic

Now suppose the column name is stored in a variable. For example, we randomly select one from a vector of column names:

cols <- c('age', 'weight', 'height')
random_col <- sample(cols, 1) 

In this case, using the dollar sign operator will not work:

df$random_col # ❌ This looks for a column literally named "random_col"

The dolar sign operator only works with literal column names- not with variables that contain column names.

Solution: Square Brackets

Instead, we can use the single square bracket extraction operators to extract the values with its preserved structure:

> df[random_col]

This returns a data frame with one column:

  weight
1    140
2    120
3    190
4    175
5    160

Or, with double square bracket extraction operators, we can extract the values, dropping the structure:

> df[[random_col]]

This returns the column as a vector:

[1] 140 120 190 175 160

Dynamic Column Extraction in a Loop

Here’s another example where the column name comes from a for loop:

for (col in cols) {
  print(df[[col]])
}

Each iteration extracts the column whose name is stored in col.

Dynamic Column Extraction in a Function

Here’s an example where the column name is passed in as part of a function:

get_mean <- function(data, col_name) {
    mean(data[[col_name]])
}

print(get_mean(df, "age"))

Because col_name is a string, we use data[[col_name]] to extract the column programmatically.

Summary

Unlock all the notes for $4

No subscriptions, no auto-renewals.

Just a simple one-time payment that helps support my free, to-the-point videos without sponsered ads.

Unlocking gets you access to the notes for this video plus all 200+ guides on this site.

Your support is appreciated. Thank you!

Payment Info

/
$4 6 months
$25 forever
Please check the form for errors
Questions? help@codewithsusan.com
← More Guides