data.table对象分配有:=来自未打印的函数内

jan*_*nyi 37 r function assignment-operator data.table

我想data.table在一个函数内修改一个.如果我:=在函数中使用该功能,则仅为第二次调用打印结果.

请看下图:

library(data.table)
mydt <- data.table(x = 1:3, y = 5:7)

myfunction <- function(dt) {
    dt[, z := y - x]
    dt
}
Run Code Online (Sandbox Code Playgroud)

当我只调用该函数时,表格不会被打印(这是标准行为.但是,如果我将返回的内容保存data.table到新对象中,则不会在第一次调用时打印,仅针对第二次调用.

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 
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么会发生这种情况以及如何预防吗?

jan*_*nyi 42

正如David Arenburg评论中提到的那样,答案可以在这里找到.版本1.9.6中修复了一个错误,但修复程序引入了这个缺点.

应该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 
Run Code Online (Sandbox Code Playgroud)

  • 只有在压缩data.table的打印时才需要`DT []`,所以当使用`:=`或`set*`函数时 (7认同)