J.P. Le Cavalier
J.P. Le Cavalier

Reputation: 1345

set data.table by reference inside a function

Here is a very light example of what I want to do.

test <- data.table(a=c(1,2,3),b=c(4,5,6))

f1 <- function(){
  test2 <- data.table(a=c(4,5,6),b=c(1,2,3))
  test <- copy(test2)
}

f1()

> test
   a b
1: 1 4
2: 2 5
3: 3 6

I would like to copy test2 into test by reference directly into the function f1() so that the output would be

> test
   a b
1: 4 1
2: 5 2
3: 6 3

I know that <- is making a copy, I would like to do the same, copying a data.table, but by reference. Is there a way to make that possible?

Thanks all!

Upvotes: 0

Views: 125

Answers (2)

Frank
Frank

Reputation: 66819

Copying by reference is an oxymoron in this context (where a "copy" has a distinct memory address).

Currently, replacing the contents of a data.table by reference cannot be done for arbitrary data.tables, since there is no way of modifying the number of rows (which may be different in test and test2) by reference.

In the special case of replacing a data.table with another having the same number of rows...

(test <- data.table(x=1:3)); address(test)
#    x
# 1: 1
# 2: 2
# 3: 3
# [1] "0000000016286280"

f1 <- function(){
  test2 <- data.table(y=LETTERS[1:3])

  test[, names(test2) := test2]
  test[, setdiff(names(test),names(test2)) := NULL]
}

f1()
test; address(test)
#    y
# 1: A
# 2: B
# 3: C
# [1] "0000000016286280"

There is probably a slicker way of achieving this goal, but I'm not sure it's a worthwhile thing to do to begin with.

Upvotes: 3

Shawn Mehan
Shawn Mehan

Reputation: 4568

Simply return out of f1

f1 <- function(){
    test2 <- data.frame(a=c(4,5,6),b=c(1,2,3))
    return(test2)
}

via

test <- f1()

yielding

> test
  a b
1 4 1
2 5 2
3 6 3

Upvotes: -2

Related Questions