0

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!

J.P. Le Cavalier
  • 1,315
  • 7
  • 16

2 Answers2

3

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.

Community
  • 1
  • 1
Frank
  • 66,179
  • 8
  • 96
  • 180
  • 1
    Thanks for your explanation Frank, I appreciate it. In my concrete example, both `test` and `test2` have the same number of rows, so I will use your suggestion. – J.P. Le Cavalier Sep 14 '15 at 13:18
-2

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
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51