0

I have a problem with this function. It gives me the modified data table I want but also changes the original one.

What I want is two different data tables. The input should remain unchanged and the modified one should give me what this exemple gives me.

if (!require('data.table')) {
  install.packages('data.table')
}

DT <- data.table(x=rnorm(10, 0, 3), y=rnorm(10, 2, 2))

func <- function(input) {

  data <- input

  data[x >= abs(1.5), c('trigger') := list(y)]
  data[y >= 3.5, c('trigger2') := list(x)]

  return (data)
}

DT_modif <- func(DT)

I don't know why I get this side effect.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
Synleb
  • 143
  • 2
  • 2
  • 13
  • This might be useful reading: http://stackoverflow.com/questions/10225098/understanding-exactly-when-a-data-table-is-a-reference-to-vs-a-copy-of-another – Heroka Mar 12 '16 at 15:55
  • Thanks Heroka. Your links is useful. – Synleb Mar 12 '16 at 16:45

1 Answers1

4

The point of data.table is that everything is passed by reference. That includes making a copy of a data table; in your code, both data and input are references to the same underlying table.

Use copy if you want a new, independent data table.

data <- copy(input)
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187