R 数据表复制和修改更改原始数据表 [英] R Data table copy and modification alters original one
问题描述
当我复制一个 data.table 并修改新的表时,原来的表会被更改,我无法找出一个.这是正常行为吗?
When I copy a data.table and modify the new one the orginal one gets altered and I cannot figure out one. Is this a normal behaviour?
dt = data.table(zone=1:5, pc=11:15)
dtt = dt
dtt[, pc := pc*2 ]
dtt
zone pc
1: 1 22
2: 2 24
3: 3 26
4: 4 28
5: 5 30
dt
zone pc
1: 1 22
2: 2 24
3: 3 26
4: 4 28
5: 5 30
更明确地创建新的data.table时我没有问题:dtt = data.table(dt)
I have no problem when creating the new data.table more explicitely: dtt = data.table(dt)
推荐答案
当你将一个新变量分配给一个已经存在的变量时,R 不会创建一个副本,而只是指向新的变量,这很好你不想复制,除非你绝对需要 - 修改时复制.
When you assign a new variable to an already existing variable, R doesn't create a copy, but just points to the new variable, which is very nice as you don't want to make copies unless you absolutely need to - copy on modify.
在此之后,由于您使用 :=
运算符,它修改 in-place(通过引用),并且因为此时,两个对象都指向相同的位置,它会反映在两个对象上.
After this, since you use the:=
operator, which modifies in-place (by reference), and since at the moment, both objects are pointing to the same location, it gets reflected on both the objects.
解决方法是显式复制 data.table
使用copy()
函数,然后通过引用分配如下:
The fix is to explicitly copy the data.table
using copy()
function and then assign by reference as follows:
dtt = copy(dt) ## dt and dtt are not pointing to same locations anymore
dtt[, pc := pc*2] ## assignment by reference doesn't affect dt
HTH
这篇关于R 数据表复制和修改更改原始数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!