包含data.table名称的变量是否已更改? [英] Variable containing data.table names changed in place?

查看:57
本文介绍了包含data.table名称的变量是否已更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许有人可以告诉我为什么在我的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) copy() $ c>。由于R的修改时复制 dt_names 仍指向与 names(DT)<相同的内存位置。因此,现在通过引用修改 DT ,例如通过添加新列, dt_names 也会得到更新。为避免这种情况,必须明确地复制: dt_names<-复制(名称(DT))

A copy() may be required when doing dt_names = names(DT). Due to R's copy-on-modify, dt_names still points to the same location in memory as names(DT). Therefore modifying DT 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屋!

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