Reputation: 59
Suppose I have a data table called "dt".
## Generate a data table
library(data.table)
dt = data.table(A=c(1,2,3),B=c(4,5,6))
I want to test some information by creating new columns but I do not want to change the original table, so I create a backup table called "test".
## Create a backup for the original table "dt"
test = dt
However, when I create a new column called "C", I find it also emerges in the original table "dt".
## Create a new column
test[,C:=A+B]
## The new column "C" emerges in the original table "dt"
> colnames(dt)
[1] "A" "B" "C"
This manipulation is likely to be dangerous because it changes the original table. How can I change the test table without changing the original table?
Upvotes: 0
Views: 32
Reputation: 389135
Use copy
:
library(data.table)
dt = data.table(A=c(1,2,3),B=c(4,5,6))
test <- copy(dt)
test[,C:=A+B]
names(test)
#[1] "A" "B" "C"
names(dt)
#[1] "A" "B"
Upvotes: 1