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.
Look at the following illustration:
library(data.table)
mydt <- data.table(x = 1:3, y = 5:7)
myfunction <- function(dt) {
dt[, z := y - x]
dt
}
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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…