Skip to content

setattr() creates a deep copy of the attribute object #1218

@tdeenes

Description

@tdeenes

I recently realized that the setattr function changes the input object by reference (that is, without any copy), however, it copies the attribute object:

library(data.table)
x <- 1
a1 <- "an attribute object which can be a large vector"
orig_addresses <- c(address(x), address(a1))
data.table::setattr(x, "a", a1)
new_addresses <- c(address(x), address(attr(x, "a")))
orig_addresses == new_addresses
# [1] TRUE FALSE

The base solution does exactly the opposite: it copies the input object, but does not copy the attribute object:

library(data.table)
x <- 1
a1 <- "an attribute object which can be a large vector"
orig_addresses <- c(address(x), address(a1))
attr(x, "a") <- a1
new_addresses <- c(address(x), address(attr(x, "a")))
orig_addresses == new_addresses
# [1] FALSE TRUE

The bit package also has a setattr function which does not create any copy:

library(data.table)
library(bit)
x <- 1
a1 <- "an attribute object which can be a large vector"
orig_addresses <- c(address(x), address(a1))
bit::setattr(x, "a", a1)
new_addresses <- c(address(x), address(attr(x, "a")))
orig_addresses == new_addresses
# [1] TRUE TRUE

Would it be possible to the modify the setattr function so that it does not create a copy of the attribute object?


sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Linux Mint LMDE

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] bit_1.1-12 data.table_1.9.5

loaded via a namespace (and not attached):
[1] tools_3.2.1 chron_2.3-45

Metadata

Metadata

Assignees

No one assigned

    Labels

    by-referenceIssues related to by-reference/copying behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions