Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setnames() affect copied tables?

Tags:

r

data.table

I want to create a copy of a data.table and change the name of a column in the new table. When I change the name of y$V1, the name of x$V1 also changes. Why is it so, and how do I avoid this behaviour?

Example:

x <- data.table(c(1,2,3),c(1,2,3))
y <- x
setnames(y, 'V1', 'new_name')
names(y) == names(x)
like image 277
321k Avatar asked Sep 25 '15 13:09

321k


People also ask

What does the setNames function do in R?

setNames: Set the Names in an Object This is a convenience function that sets the names on an object and returns the object. It is most useful at the end of a function definition where one is creating the object to be returned and would prefer not to store it under a name just so the names can be assigned.

What package is setNames R?

setNames is available in stats package, used to name the elements in a vector.


1 Answers

Because R implements simple reference counting, and generally only copies on modification and not on assignment. So y = x for any x and y would not copy anything, and no new objects will be created.

Combined with the fact that some data.table functions can modify the object without copying, like setnames, you get the effect you see.

Use copy as Frank mentioned to force an explicit copy.

like image 73
eddi Avatar answered Nov 12 '22 15:11

eddi