How to Apply the Same Function to Every Specified Data Table Variable in R (Example Code)

In this R tutorial you’ll learn how to use the same function for a predefined set of variables.

Setting up the Example

install.packages("data.table")                                       # Install & load data.table package
library("data.table")
my_tab <- data.table(w = 1:5,                                      # Creating data.table
                     x = c(3, 7, 5, 7, 8),
                     y = LETTERS[1:5],
                     z = 1)
my_tab                                                             # Return data.table to console
#    w x y z
# 1: 1 3 A 1
# 2: 2 7 B 1
# 3: 3 5 C 1
# 4: 4 7 D 1
# 5: 5 8 E 1

Example: Applying the Same Function to Certain Variables of data.table

mod_cols <- c("w", "x", "z")                                       # Variables to be modified
my_tab[ , (mod_cols) := lapply(.SD, "+", 10), .SDcols = mod_cols]  # Modify data
my_tab                                                             # Return new data.table
#     w  x y  z
# 1: 11 13 A 11
# 2: 12 17 B 11
# 3: 13 15 C 11
# 4: 14 17 D 11
# 5: 15 18 E 11

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.
You need to agree with the terms to proceed

Menu
Top