在函数内通过引用设置 data.table
set data.table by reference inside a function
这是我想做的一个非常简单的例子。
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
我想通过引用直接将 test2
复制到 test
到函数 f1()
中,这样输出将是
> test
a b
1: 4 1
2: 5 2
3: 6 3
我知道<-
正在复制,我也想复制一份data.table,不过是引用。有没有办法让它成为可能?
谢谢大家!
f1
中的 return
f1 <- function(){
test2 <- data.frame(a=c(4,5,6),b=c(1,2,3))
return(test2)
}
通过
test <- f1()
屈服
> test
a b
1 4 1
2 5 2
3 6 3
在这种情况下,通过引用复制是矛盾的(其中 "copy" 具有不同的内存地址)。
目前,通过引用替换 data.table 的内容无法在任意 data.table 秒内完成,因为 there is no way of modifying the number of rows(这可能在 test
和 test2
中有所不同)以供参考。
在将 data.table 替换为具有相同行数的另一个的特殊情况下...
(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"
可能有一种更巧妙的方法可以实现这个目标,但我不确定从一开始这样做是否值得。
这是我想做的一个非常简单的例子。
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
我想通过引用直接将 test2
复制到 test
到函数 f1()
中,这样输出将是
> test
a b
1: 4 1
2: 5 2
3: 6 3
我知道<-
正在复制,我也想复制一份data.table,不过是引用。有没有办法让它成为可能?
谢谢大家!
f1
f1 <- function(){
test2 <- data.frame(a=c(4,5,6),b=c(1,2,3))
return(test2)
}
通过
test <- f1()
屈服
> test
a b
1 4 1
2 5 2
3 6 3
在这种情况下,通过引用复制是矛盾的(其中 "copy" 具有不同的内存地址)。
目前,通过引用替换 data.table 的内容无法在任意 data.table 秒内完成,因为 there is no way of modifying the number of rows(这可能在 test
和 test2
中有所不同)以供参考。
在将 data.table 替换为具有相同行数的另一个的特殊情况下...
(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"
可能有一种更巧妙的方法可以实现这个目标,但我不确定从一开始这样做是否值得。