:=(通过引用传递)操作符在data.table包中同时修改另一个数据表对象 [英] := (pass by reference) operator in the data.table package modifies another data table object simultaneously

查看:88
本文介绍了:=(通过引用传递)操作符在data.table包中同时修改另一个数据表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试我的代码时,我发现了如下:如果我将一个data.table DT1 分配给 DT 然后改变 DT ,随后改变 DT1 。因此, DT DT1 似乎内部链接。这是预期的行为吗?虽然我不是一个编程专家,这看起来不对,我用简单的R变量或一个 data.frame 测试它,我无法重现的行为。这里发生了什么?

  DF < -  data.frame(ID = letters [1:5],
value = 1:5)
DF1 < - DF
all.equal(DF1,DF)
[1] TRUE
DF [1,value] < - DF [1,value] * 2
all.equal(DF1,DF)
[1]组件2:平均相对差异:1

库表)
data.table 1.7.1对于帮助类型:help(data.table)
DT< - data.table(ID = letters [1:5],
value = 1:5)
DT1 < - DT
all.equal(DT1,DT)
[1] TRUE
DT [,value:= value * 2]
ID值
[1,] a 2
[2,] b 4
[3,] c 6
[4,] d 8
[5 ,] e 10
all.equal(DT1,DT)
[1] TRUE


c> c> c> c> ? data.table :: copy


不返回任何值。数据表通过引用修改。如果需要复印,请首先复印(使用DT2 =复印(DT))。 copy()在以下情况之前有时也很有用:=用于通过引用对列进行子分配。



While testing my code, I found out the following: If I assign a data.table DT1 to DT and change DT afterwards, DT1 changes with it. So DT and DT1 seem to be internally linked. Is this intended behavior? Although I'm not a programming expert, this looks wrong to me, and testing it with simple R variables or a data.frame, I couldn't reproduce the behavior. What's happening here?

DF <- data.frame(ID=letters[1:5],
                  value=1:5)
DF1 <- DF
all.equal(DF1, DF)
[1] TRUE
DF[1, "value"] <- DF[1, "value"]*2
all.equal(DF1, DF)
[1] "Component 2: Mean relative difference: 1"

library(data.table)
data.table 1.7.1  For help type: help("data.table")
DT <- data.table(ID=letters[1:5],
                  value=1:5)
DT1 <- DT
all.equal(DT1, DT)
[1] TRUE
DT[, value:=value*2]
     ID value
[1,]  a     2
[2,]  b     4
[3,]  c     6
[4,]  d     8
[5,]  e    10
all.equal(DT1, DT)
[1] TRUE

解决方案

This piece of documentation in data.table would help. ? data.table::copy

No value is returned. The data.table is modified by reference. If you require a copy, take a copy first (using DT2=copy(DT)). copy() may also sometimes be useful before := is used to subassign to a column by reference.

这篇关于:=(通过引用传递)操作符在data.table包中同时修改另一个数据表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆