使用 := 从函数内部分配的 data.table 对象未打印 [英] data.table objects assigned with := from within function not printed
问题描述
我想在函数中修改 data.table
.如果我在函数中使用 :=
功能,则只为第二次调用打印结果.
I would like to modify a data.table
within a function. If I use the :=
feature within the function, the result is only printed for the second call.
看下图:
library(data.table)
mydt <- data.table(x = 1:3, y = 5:7)
myfunction <- function(dt) {
dt[, z := y - x]
dt
}
当我只调用函数时,不会打印表格(这是标准行为.但是,如果我将返回的 data.table
保存到新对象中,则不会在第一次调用,只为第二次调用.
When I call only the function, the table is not printed (which is the standard behaviour. However, if I save the returned data.table
into a new object, it is not printed at the first call, only for the second one.
myfunction(mydt) # nothing is printed
result <- myfunction(mydt)
result # nothing is printed
result # for the second time, the result is printed
mydt
# x y z
# 1: 1 5 4
# 2: 2 6 4
# 3: 3 7 4
您能解释一下为什么会发生这种情况以及如何预防吗?
Could you explain why this happens and how to prevent it?
推荐答案
正如 David Arenburg 在一篇 comment,可以找到答案
As David Arenburg mentions in a comment, the answer can be found here. There was a bug fixed in the version 1.9.6 but the fix introduced this downside.
应该在函数末尾调用 DT[]
来防止这种行为.
One should call DT[]
at the end of the function to prevent this behaviour.
myfunction <- function(dt) {
dt[, z := y - x][]
}
myfunction(mydt) # prints immediately
# x y z
# 1: 1 5 4
# 2: 2 6 4
# 3: 3 7 4
这篇关于使用 := 从函数内部分配的 data.table 对象未打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!