2013-03-22 94 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