R Yoda
R Yoda

Reputation: 8760

Append a data.table to another data.table by reference similar to rbind

I want to append ("rbind") a data.table object at the end of another data.table object within a function without returning the combined result but appending directly to the first data table object so that I do not have to assign the function result to the first data.table again.

Since a data.table is passed by reference as function argument it could be possible but rbind and rbindlist do always create a new result object instead of appending to an existing data.table object.

How can I do this?

library(data.table)

dt1 <- data.table(a = 1, b = "hello")
dt2 <- data.table(a = 2, b = "world")

dt.all <- data.table::rbindlist(list(dt1, dt2))

dt.all
#    a     b
# 1: 1 hello
# 2: 2 world


dt.append <- function(x1, x2) {
  x1 <- data.table::rbindlist(list(x1, x2))  # does not change the outer data.table!
  invisible()
}

dt.append(dt1, dt2)

dt1   # I would like to see both rows here
#    a     b
# 1: 1 hello

Upvotes: 5

Views: 7731

Answers (1)

akrun
akrun

Reputation: 887158

We need to assign it to the object in the global environment. In the OP's function, it is assigned locally to an object named 'x1' and one of the nice things about functions it that the global objects are not mutated (local scope)

dt.append <- function(x1, x2) {
  obj <- deparse(substitute(x1)) # get the actual object name as a string
  assign(obj, value = data.table::rbindlist(list(x1, x2)), envir = .GlobalEnv)

 }

dt1
#   a     b
#1: 1 hello
#2: 2 world

Upvotes: 7

Related Questions