data.table in place modification in R

1k views Asked by At

Consider a data.table DT as follows.

DT <- iris
setDT(DT)
ad <- address(DT)

DT[, a := NA_integer_]
identical(address(DT), ad)

I am trying to insert the some information sequentially in DT$a using a loop.

a1 <- sample(1:1000, 50)
a2 <- sample(1:1000, 50)
a3 <- sample(1:1000, 50)

As you can see this leads to copying of DT for the follwing method.

DT$a[1:50] <- a1
identical(address(DT), ad)

How to do this using data.table avoiding copying of DT?

1

There are 1 answers

0
grrgrrbla On BEST ANSWER
for (i in 1:3) DT[1:(50*i), a := sample(1:1000, 50)]

or which makes more sense:

DT[ , a := sample(1:1000, 150)]