【问题标题】:data.table objects assigned with := from within function not printed使用 := 从函数内部分配的 data.table 对象未打印
【发布时间】:2021-11-16 17:27:52
【问题描述】:

我想在函数中修改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 

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

【问题讨论】:

标签: r function data.table assignment-operator


【解决方案1】:

正如David Arenburgcomment 中提到的那样,可以在here 中找到答案。在 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 

【讨论】:

  • DT[] 仅在打印 data.table 被抑制时才需要,因此在使用 :=set* 函数时
【解决方案2】:

对不起,如果我不应该在这里发布一些不是 回答,但我的帖子太长,无法发表评论。

我想指出 janosdivenyi 添加一个 尾随 []dt 并不总是给出预期的结果(即使 当使用 data.table 1.9.6 或 1.10.4) 时,如下所示。

下面的例子表明如果dt是函数的最后一行 在不存在的情况下获得所需的行为 尾随 [],但如果 dt 不在函数的最后一行,则 需要尾随 [] 才能获得所需的行为。

第一个示例表明,dt 上没有尾随 [],我们得到 dt 在函数的最后一行时的预期行为

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

myfunction <- function(dt) {
  df <- 1
  dt[, z := y - x]
}

myfunction(mydt)  # Nothing printed as expected

mydt  # Content printed as desired
##    x y z
## 1: 1 5 4
## 2: 2 6 4
## 3: 3 7 4

dt 上添加尾随[] 会导致意外行为

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

myfunction <- function(dt) {
  df <- 1
  dt[, z := y - x][]
}

myfunction(mydt)  # Content printed unexpectedly
##    x y z
## 1: 1 5 4
## 2: 2 6 4
## 3: 3 7 4

mydt  # Content printed as desired
##    x y z
## 1: 1 5 4
## 2: 2 6 4
## 3: 3 7 4

df &lt;- 1 移动到没有尾随[] 的dt 之后会产生意外 行为

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

myfunction <- function(dt) {
  dt[, z := y - x]
  df <- 1
}

myfunction(mydt)  # Nothing printed as expected

mydt  # Nothing printed unexpectedly

在 dt 之后移动 df &lt;- 1 并带有尾随 [] 给出预期 行为

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

myfunction <- function(dt) {
  dt[, z := y - x][]
  df <- 1
}

myfunction(mydt)  # Nothing printed as expected

mydt  # Content printed as desired
##    x y z
## 1: 1 5 4
## 2: 2 6 4
## 3: 3 7 4

【讨论】:

  • 我认为您部分混淆了函数的工作原理。所有函数都返回一个值。如果您不编写显式 return(x) 语句,则返回函数中的最后一个值。 df &lt;- 1 返回值 1 invisibly, while DT[, x := y][]` 返回 DT,打印。
  • 感谢您的解释。我没有意识到。我想这是让我着迷的“隐形回归”。我也对数据表的“通过引用复制”方面感到困惑。我花了很长时间研究这些例子,试图理解它们。你现在明白我为什么不在这个论坛上回答问题了:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多