我想在一个函数中修改一个data.table
.如果我在函数中使用:=
特性,结果只会在第二次调用时打印出来.
请看下图:
library(data.table)
mydt <- data.table(x = 1:3, y = 5:7)
myfunction <- function(dt) {
dt[, z := y - x]
dt
}
当我只调用函数时,表不会被打印(这是标准行为.但是,如果我将返回的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
你能解释一下为什么会发生这种情况以及如何预防吗?