Remove Multiple Columns from data.table in R (Example)
In this tutorial, I’ll illustrate how to delete several data.table variables in R.
The content of the tutorial is structured like this:
Let’s dive right into the example…
Example Data & Packages
We first need to install and load the data.table package, if we want to use the functions that are contained in the package:
install.packages("data.table") # Install & load data.table library("data.table")
Now, we can create a data.table as example data as shown below:
data <- data.table(x1 = letters[1:4], # Example data.table x2 = 3, x3 = 1:4) data # Print data.table # x1 x2 x3 # 1: a 3 1 # 2: b 3 2 # 3: c 3 3 # 4: d 3 4
As you can see based on the previous RStudio console output, our example data consists of four rows and three variables.
Example: Removing Several Variables from data.table in One Line of Code
This Example illustrates how to delete two variables from a data.table simultaneously. Consider the following R code:
data[ ,`:=`(x1 = NULL, x2 = NULL)] # Remove columns data # Print updated data.table # x3 # 1: 1 # 2: 2 # 3: 3 # 4: 4
As you can see based on the previous output, our updated data.table contains only the column x3. The variables x1 and x were removed.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. In the video, I explain the examples of this tutorial in RStudio:
The YouTube video will be added soon.
Furthermore, you could read the related articles on https://statisticsglobe.com/.
- Apply Function to data.table in Each Specified Column
- Remove Data Frame Columns by Name
- Introduction to the data.table Package
- The R Programming Language
Summary: In this tutorial, I showed how to get rid of multiple data.table columns in R. Let me know in the comments section, if you have any additional 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.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
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.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.






