我想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)
你能解释一下为什么会发生这种情况以及如何预防吗?