2015-10-07 56 views
27

我想在函數內修改data.table。如果在功能中使用:=功能,則只會爲第二個呼叫打印結果。從函數返回後不打印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 

你能解釋一下爲什麼出現這種情況,如何預防呢?

+4

閱讀:https://github.com/Rdatatable/data.table/blob/master /NEWS.md#bug-fixes-3。第1.9版中修復的第一個BUG。6 –

+0

請參閱'data.table'常見問題的2.23節('vignette(「datatable-faq」,package =「data.table」)') – Uwe

回答

29

由於David Arenburg提到comment,答案可以找到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 
+5

只有當data.table的打印被抑制時才需要'DT []' ,所以當使用':='或'set *'函數 – jangorecki

0

對不起,如果我不應該張貼在這裏的東西,這不是一個 答案,但我的文章太長了評論。

我想指出,加入 (使用data.table 1.9.6或1.10.4時甚至 )爲我做下面尾隨[]dt並不總是產生預期的結果的那janosdivenyi的解決方案。

以下實施例顯示,如果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 <- 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 <- 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 
+1

時,我認爲你對函數的工作方式有些困惑。所有函數都返回一個值。如果你不寫一個顯式的'return(x)'語句,那麼返回函數中的最後一個值。 'df < - 1'無形地返回值'1',而'DT [,x:= y] []'返回'DT',打印出來。 – Frank

+1

感謝您的解釋。我沒有意識到。我猜這就是我無法迴避的「迴歸」。我也被數據表的「引用複製」方面所困惑。我花了很多年玩這些例子試圖理解它們。你現在明白了爲什麼我不在這個論壇上回答問題:-) – Paul