title: data.table weird behaviour when used in a function
body: <p>I have a <code>data.frame</code> as follows.</p>
  
  <pre><code>data &lt;- structure(list(V1 = structure(1:3, .Label = c("S01", "S02", "S03"), class = "factor"), V2 = structure(c(1L, 3L, 2L), .Label = c("Alan", "Bruce", "Jay"), class = "factor"), V3 = structure(c(3L, 1L, 2L), .Label = c("Barry", "Dick", "Hal"), class = "factor"), V4 = structure(c(1L, 3L, 2L), .Label = c("Guy", "Jean-Paul", "Wally"), class = "factor"), V5 = structure(c(3L, 1L, 2L), .Label = c("Bart", "Damien", "John"), class = "factor")), .Names = c("V1", "V2", "V3", "V4", "V5"), class = "data.frame", row.names = c(NA, -3L))
  </code></pre>
  
  <p>It is not a <code>data.table</code></p>
  
  <pre><code>is.data.table(data)
  [1] FALSE
  </code></pre>
  
  <p>I have a function <code>foo</code> for example which utilizes <code>data.table</code> for doing some manipulations in the <code>data.frame</code> as follows. </p>
  
  <pre><code>foo &lt;- function(df) {
    if(!is.data.frame(df)) stop('"df" is not a data.frame')
    setDT(df)
    setkey(df, V1)
    df[, "NEW" := paste0(V3, V4), with = FALSE]
    setDF(df)
    return(df)
  }
  </code></pre>
  
  <p>However when I run the function with the <code>data.frame</code> <code>data</code> (not a <code>data.table</code>), the output <code>out</code> is a <code>data.frame</code> (because of <code>setDF(df)</code>).</p>
  
  <pre><code>out &lt;- foo(data)
  is.data.table(out)
  [1] FALSE
  </code></pre>
  
  <p>But now the original <code>data.frame</code> <code>data</code> is a <code>data.table</code>.</p>
  
  <pre><code>is.data.table(data)
  [1] TRUE
  </code></pre>
  
  <p>I understand this is because <code>data.table</code> works by reference. However how to deal with this when being used in a function. I dont' wan't to inadvertently change any data.frame in environment. Should I always force copy with <code>copy</code> or <code>&lt;-</code> instead of <code>setDT</code> whenever <code>data.table</code> is used in a function, or is there another way?</p>