2013-03-22 92 views
4

我是data.table的新手,我遇到了這個類的問題。修改data.table中的值R

我有一個表(data1)與2列:夫婦和比率。夫妻是data.table的關鍵。

我想修改表中的一個值。

當我寫了下面的代碼:

(cple is an existing value of Couple) 

data1[cple]$Ratio[1]<-0 #I get more than 50 warnings and it doesn't work 

data1$Ratio[1]<-0 # It works perfectly (but it's not the same as the above code) 

的錯誤似乎有事情做的鑰匙,但我想不出什麼?

下面是一個例子:

>data1<-data.table(Couple=c("a","a","b","b"),Ratio=1:4) 
>data1 
    Couple Ratio 
1:  a  1 
2:  a  2 
3:  b  3 
4:  b  4 
>setkey(data1,Couple) 

>data1["a"]$Ratio[1]<-2 #doesn't work warning message 

WARNING: 
#In `[<-.data.table`(`*tmp*`, "a", value = list(Couple = c("a", "a" : 
# Coerced 'double' RHS to 'integer' to match the column's type; may have truncated precision. Either change the target column to 'double' first (by creating a new 'double' vector length 4 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'integer' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please. 


>data1$Ratio[1]<-2 #works 
>data1 
    Couple Ratio 
1:  a  2 
2:  a  2 
3:  b  3 
4:  b  4 

感謝

+1

你好!請讓你的文章重現。閱讀這篇文章[**如何做一個偉大的重現示例**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)關於如何做到這一點。謝謝。 – Arun 2013-03-22 14:46:13

+0

如果你的data.table沒有太多的行,嘗試粘貼'dput(data1)'的輸出。 (或者使用'dput(head(data1))')。 – 2013-03-22 14:54:21

回答

4

從你的問題的第一部分來看要真正地做這樣的事情:

data1[cple,Ratio:=c(0L,Ratio[-1])] 

這確實爲cple在data.table鍵的值二進制搜索和作品然後在這個子集。整數零與Ratio值相結合,第一個值除外,結果矢量參考Ratio進行分配。

5

你不應該當你將data.table使用$data.table是女兒類data.frame但它是因爲它可以更新更好通過引用,沒有副本。每次您嘗試使用$(如data1$Ratio[1]<-2)進行分配時,它都會複製整個表格。您應該查看vignette,尤其是更新:=運營商。在你的情況`data1 [Couple =='a',Ratio:= c(0L,Ratio [-1])]是你想要的。

您可能也想閱讀這個非常好的post

+0

@Roland,謝謝,你能簡單地詳細說明你答案的語法嗎? – 2013-03-22 15:29:38