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/.

 

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.

 



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.

Menu
Top