[R] Confusing behaviour in data.table: unexpectedly changing variable

Matthew Dowle mdowle at mdowle.plus.com
Wed Sep 25 09:18:24 CEST 2013


Very sorry to hear this bit you.  If you need a copy of names before 
changing them by reference :

     oldnames <- copy(names(DT))

This will be documented and it's on the bug list to do so. copy is 
needed in other circumstances too, see ?copy.

More details here :

http://stackoverflow.com/questions/18662715/colnames-being-dropped-in-data-table-in-r
http://stackoverflow.com/questions/15913417/why-does-data-table-update-namesdt-by-reference-even-if-i-assign-to-another-v

Btw, the r-help posting guide says (last time I looked) you should only 
post to r-help about packages if you have tried the maintainer first but 
didn't hear from them; i.e., r-help isn't for support about packages.

I don't follow r-help, so please continue to cc me if you reply.

Matthew

On 25/09/13 00:47, Jonathan Dushoff wrote:
> I got bitten badly when a variable I created for the purpose of
> recording an old set of names changed when I didn't think I was going
> near it.
>
> I'm not sure if this is a desired behaviour, or documented, or warned
> about.  I read the data.table intro and the FAQ, and also ?setnames.
>
> Ben Bolker created a minimal reproducible example:
>
> library(data.table)
> DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
> names(DT)
> ## [1] "x" "y" "v"
>
> oldnames <- names(DT)
> print(oldnames)
> ## [1] "x" "y" "v"
>
> setnames(DT, LETTERS[1:3])
> print(oldnames)
> ## [1] "A" "B" "C"
>



More information about the R-help mailing list