# Apply Function to data.table in Each Specified Column in R (Example)

This page shows how to **use the same function for a predefined set of variables** in the R programming language.

Table of contents:

Let’s take a look at some R codes in action…

## Example Data & Packages

For this tutorial, we first need to install and load the data.table package:

install.packages("data.table") # Install data.table package library("data.table") # Load data.table |

install.packages("data.table") # Install data.table package library("data.table") # Load data.table

Now, we can create a data.table in R as follows:

data <- data.table(x1 = 1:5, # Create data.table x2 = letters[1:5], x3 = 3) data # Print example data # x1 x2 x3 # 1: 1 a 3 # 2: 2 b 3 # 3: 3 c 3 # 4: 4 d 3 # 5: 5 e 3 |

data <- data.table(x1 = 1:5, # Create data.table x2 = letters[1:5], x3 = 3) data # Print example data # x1 x2 x3 # 1: 1 a 3 # 2: 2 b 3 # 3: 3 c 3 # 4: 4 d 3 # 5: 5 e 3

Have a look at the previous output of the RStudio console. It shows that our data.table consists of five rows and three columns.

## Example: Apply Function to Each Specified data.table Column Using lapply, .SD & .SDcols

In this Section, I’ll explain how to call a function for certain variables of a data.table using a combination of the lapply, .SD, and .SDcols functions. Consider the following list of variable names:

mod_cols <- c("x1", "x3") # Columns that should be modified |

mod_cols <- c("x1", "x3") # Columns that should be modified

Now, we can apply the following line of R code to compute the power of 2 for each cell of the specified columns:

data[ , (mod_cols) := lapply(.SD, "^", 2), .SDcols = mod_cols] # Modify data |

data[ , (mod_cols) := lapply(.SD, "^", 2), .SDcols = mod_cols] # Modify data

data # Print updated data # x1 x2 x3 # 1: 1 a 9 # 2: 4 b 9 # 3: 9 c 9 # 4: 16 d 9 # 5: 25 e 9 |

data # Print updated data # x1 x2 x3 # 1: 1 a 9 # 2: 4 b 9 # 3: 9 c 9 # 4: 16 d 9 # 5: 25 e 9

As you can see based on the previous RStudio console output, our data was updated.

## Video, Further Resources & Summary

Do you want to learn more about the application of functions to columns? Then you might watch the following video of my YouTube channel. In the video, I show the R programming codes of this tutorial.

*The YouTube video will be added soon.*

Besides the video, you may read the other R tutorials of my website.

- Apply Function to Every Row of Data Frame or Matrix in R
- data.table Package in R
- The R Programming Language

This tutorial illustrated how to **call the same function for a list of variables of a data.table** in the R programming language. Tell me about it in the comments, if you have any additional questions.

**5**/

**5**(

**1**vote )

### Subscribe to my free statistics newsletter: