0

I have a function that parses an XML-document to a data.table using among others the :=-operator. When I return the data.table from the parser-function, nothing gets displayed the first time I call the result, only the second call creates the output I want.

I suspect it has something to do with data.table's way of evaluating assignments. My question now is: how do I avoid the first empty call (so to say, how do I force data.table to evaluate the expression)?

To give a small example:

my_fun <- function() {
  dt <- data.table(x = 1) 
  dt[, y := 2]
  return(dt)
}

my_dt <- my_fun()

my_dt
# ... nothing happens

my_dt
# x y
# 1: 1 2

One possible solution is to call copy within the function, but I am unsure if that is the data.table-way of doing things (with regards to speed and memory usage). An example of this is:

my_fun2 <- function() {
  dt <- data.table(x = 1)
  dt[, y := 2]
  dt <- copy(dt)
  return(dt)
}

my_dt2 <- my_fun2()
my_dt2
# x y
# 1: 1 2
David
  • 9,216
  • 4
  • 45
  • 78
  • Probably; you may accumulate a downvote or two if you leave this up. It gets asked fairly often, but is kind of hard to search for. – nrussell Dec 02 '16 at 15:10
  • Well, if this helps another user, then I take the downvotes... :) – David Dec 02 '16 at 15:11

0 Answers0