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)
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.
setNames is available in stats package, used to name the elements in a vector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With