修改R中data.table中的值

时间:2013-03-22 14:45:01

标签: r data.table

我是data.table的新手,我遇到了这个类的问题。

我有一个包含2列的表(data1):Couple和Ratio。情侣是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)

错误似乎与Keys有关,但我无法弄清楚是什么?

以下是一个例子:

 >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

由于

2 个答案:

答案 0 :(得分:8)

当您将ASSIGN $作为data.table的女儿类时,不应将data.tabledata.frame一起使用,但它更好,因为它可以通过引用更新,副本。每次尝试使用$ data1$Ratio[1]<-2进行分配时,都会复制整个表格。您应该查看vignette,尤其是更新:=运算符。在你的情况下`data1 [Couple =='a',Ratio:= c(0L,Ratio [-1])]就是你想要的。

您可能也希望阅读这篇非常好的post

答案 1 :(得分:4)

从问题的第一部分来看,你想要真正做到这样的事情:

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

这会在data.table键中对cple的值进行二进制搜索,然后对此子集进行操作。除了第一个值之外,整数零与Ratio值组合在一起,并且通过引用Ratio来分配结果向量。