包含data.table名称的变量是否已更改? [英] Variable containing data.table names changed in place?
问题描述
也许有人可以告诉我为什么在我的data.table中添加一列后(而不重新分配它们)我分配给 idVars的名称为什么改变了?我该如何坚持只存储前两个列名的分配?
Maybe some can tell me why the names I assigned to "idVars" are changing after adding a column to my data.table (without reassigning them)? How can I persist the assignment to store only the first two column names?
谢谢!
library(data.table)
DT <- data.table(a=1:10, b=1:10)
idVars <- names(DT)
print(idVars)
# [1] "a" "b"
DT[, "c" := 1:10]
print(idVars)
# [1] "a" "b" "c"
# devtools::session_info()
# data.table * 1.11.6 2018-09-19 CRAN (R 3.5.1)
推荐答案
我们可以创建名称
的副本
作为名称(DT)
和'idVars'具有相同的内存位置
We can create a copy
of the names
as the names(DT)
and the 'idVars' have the same memory location
tracemem(names(DT))
#[1] "<0x7f9d74c99600>"
tracemem(idVars)
#[1] "<0x7f9d74c99600>"
因此,请为以下内容创建副本
名称
So, instead create a copy
of the names
idVars <- copy(names(DT))
tracemem(idVars)
#[1] "<0x7f9d7d2b97c8>"
并且分配后不会改变
DT[, "c" := 1:10]
idVars
#[1] "a" "b"
根据?copy
:
执行
dt_names = names(DT)$ c时可能需要
copy()
$ c>。由于R的修改时复制,dt_names
仍指向与names(DT)<相同的内存位置
。因此,现在通过引用修改DT
,例如通过添加新列,dt_names
也会得到更新。为避免这种情况,必须明确地复制:dt_names<-复制(名称(DT))
。
A
copy()
may be required when doingdt_names = names(DT)
. Due to R's copy-on-modify,dt_names
still points to the same location in memory asnames(DT)
. Therefore modifyingDT
by reference now, say by adding a new column,dt_names
will also get updated. To avoid this, one has to explicitly copy:dt_names <- copy(names(DT))
.
这篇关于包含data.table名称的变量是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!