用 := 分配的 data.table 对象来自未打印的函数内 [英] data.table objects assigned with := from within function not printed

查看:22
本文介绍了用 := 分配的 data.table 对象来自未打印的函数内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改一个函数内的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 保存到一个新对象中,它不会打印在第一次调用,仅用于第二次调用.

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?

推荐答案

正如 David ArenburgDavid Arenburg 中提到的a href="https://stackoverflow.com/questions/32988099/data-table-objects-not-printed-after-returned-from-function#comment53801457_32988099">评论,可以找到答案此处.在 1.9.6 版本中修复了一个错误,但该修复引入了这个缺点.

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[] 以防止这种行为.

One should call DT[] at the end of the function to prevent this behaviour.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆