R How to Append Several Variables to data.table (Example Code)

This tutorial explains how to append several new data.table variables in the R programming language.

Preparing the Example

install.packages("data.table")                 # Install & load data.table package
library("data.table")
data(iris)                                     # Load iris data set
iris_dt <- as.data.table(iris)                 # Convert iris to data.table
head(iris_dt)                                  # Show head of data.table in RStudio
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1:          5.1         3.5          1.4         0.2  setosa
# 2:          4.9         3.0          1.4         0.2  setosa
# 3:          4.7         3.2          1.3         0.2  setosa
# 4:          4.6         3.1          1.5         0.2  setosa
# 5:          5.0         3.6          1.4         0.2  setosa
# 6:          5.4         3.9          1.7         0.4  setosa
new1 <- 1:nrow(iris_dt)                        # Create two vector objects in R
head(new1)
# [1] 1 2 3 4 5 6
new2 <- nrow(iris_dt):1
head(new2)
# [1] 150 149 148 147 146 145

Example: Appending Multiple Vectors as New Columns to data.table

iris_dt[ , `:=` (new1 = new1, new2 = new2)]    # Adding new variables to data.table
head(iris_dt)                                  # Show new data.table in RStudio
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species new1 new2
# 1:          5.1         3.5          1.4         0.2  setosa    1  150
# 2:          4.9         3.0          1.4         0.2  setosa    2  149
# 3:          4.7         3.2          1.3         0.2  setosa    3  148
# 4:          4.6         3.1          1.5         0.2  setosa    4  147
# 5:          5.0         3.6          1.4         0.2  setosa    5  146
# 6:          5.4         3.9          1.7         0.4  setosa    6  145

Further Resources & Related Tutorials

You may find some additional R tutorials on topics such as variables and loops below:

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