data.table对象在从函数返回后不打印 [英] data.table objects not printed after returned from function
问题描述
我想在函数中修改 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
保存到一个新对象,它不会在第一次调用时打印,只有第二次调用。 / p>
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
你能解释为什么会发生这种情况, / p>
Could you explain why this happens and how to prevent it?
推荐答案
由于 David Arenburg 在评论中提及,可以在此处找到答案。
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 []
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屋!