修改R中data.table中的值

Ric*_*bby 4 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)
Run Code Online (Sandbox Code Playgroud)

错误似乎与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
Run Code Online (Sandbox Code Playgroud)

谢谢

sta*_*ant 8

你不应该使用$data.table当你将data.table是一个女儿类的data.frame,但它是更好,因为它可以通过参考更新,无需拷贝.每次尝试与分配$喜欢data1$Ratio[1]<-2它复制整个表.您应该查看插图,尤其是更新:=操作符.在你的情况下`data1 [Couple =='a',Ratio:= c(0L,Ratio [-1])]就是你想要的.

您可能也想阅读这篇非常好的帖子.


Rol*_*and 5

从问题的第一部分来看,您实际上想执行以下操作:

data1[cple,Ratio:=c(0L,Ratio[-1])]
Run Code Online (Sandbox Code Playgroud)

cple将对data.table键中的值进行二进制搜索,然后对该子集起作用。整数零与Ratio除第一个值以外的值组合,并且通过参考分配所得的向量Ratio