Learn R Programming

dtlg (version 0.0.2)

maybe_copy_dt: Return a data.table by reference or by value

Description

maybe_copy_dt() returns its input as a data.table, with behaviour controlled by the global copy semantics option dt_copy_semantics().

Usage

maybe_copy_dt(x)

Value

A data.table. Whether the return value aliases the input depends on the semantics:

  • "reference": input is mutated in place, aliasing guaranteed if x is already a data.table.

  • "value": a fresh copy is returned, independent of the input.

Arguments

x

A data.table or data.frame.

Details

  • If the semantics are "reference" (default):

    • If x is already a data.table, it is returned unchanged. Aliasing holds, so mutations with := will affect both input and output.

    • If x is a data.frame, it is converted to a data.table in place via data.table::setDT(), mutating the caller’s object. The returned object is a data.table with the same contents. For efficiency, the column vectors are reused without a deep copy.

  • If the semantics are "value":

    • x is converted to a data.table (if necessary) and a deep copy is returned. Mutating the result does not affect the input.

See Also

dt_copy_semantics(), set_dt_copy_semantics()

Examples

Run this code
# Default: reference semantics
df <- data.frame(a = 1:3)
out <- maybe_copy_dt(df)
data.table::is.data.table(df) # TRUE, converted in place

# Switch to value semantics
old <- set_dt_copy_semantics("value")
dt <- data.table::data.table(a = 1:3)
out2 <- maybe_copy_dt(dt)
out2[, b := 99L]
"b" %in% names(dt)  # FALSE, original unchanged

# Restore previous semantics
set_dt_copy_semantics(old)

Run the code above in your browser using DataLab