Removing data table columns inside a function

I have the following example:

irisDT <- as.data.table(iris)

mod <- function(dat) {
  dat[, index:=(1:nrow(dat))]
  setkey(dat, index)

  dat <- dat[2:10]

  dat[, index:=NULL]
  invisible()
}

mod(irisDT)
names(irisDT) # it contains index

To my surprise, the index column still exists after the mod() function call . This is not the case when I delete a row dat <- dat[2:10]. I assume that since rows cannot be deleted by reference, another data table is created. However, I would like to remove the index column in the original data.table.

+5
source share
1 answer

Great question. data.table copied-on-change, on <-, in the usual R-mode.

He was not copied to replace :=or set*( setkey, setnames, setattr), provided by the package data.table.

, - data.table, , , data.frame. , , . <- -- data.table. :=, , .

, , R, .

, , (. copy()).

+5

All Articles