修改R中data.table中的值 [英] Modifying a value in a data.table in R

查看:207
本文介绍了修改R中data.table中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个带有2列的表(data1):夫妻和比率。夫妇是data.table的键。



我试图修改表中的值。



当我写下面的代码:

 (cple是Couple的现有值)

data1 [cple] $ Ratio [1]< -0#获得超过50个警告,它不工作

data1 $ Ratio [1]< -0#它和上面的代码不一样)

错误似乎与关键字有关,但是不能弄清楚什么?



下面是一个示例:

 > data1< .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#不工作警告消息

警告:
#In`[< `,a,value = list(Couple = c(a,a:
#Coerced'double'RHS to'integer'to match the column's type; may have truncated precision。 (通过创建新的双向量向量长度4(整个表的行)并分配它,即替换列),或将RHS强制为整数(例如1L,NA_ [real |整数] _,作为*,等),以使您的意图清楚和速度。或者,当您创建表并坚持它,请正确设置列类型


> data1 $ Ratio [1]< -2 #works
> data1
夫妇比例
1:a 2
2:a 2
3 :b 3
4:b 4

感谢


<从你的问题的第一部分,你想实际做这样的事情:

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


$ b b

这样做在数据表键中的二进制搜索 cple ,然后在这个子集上工作。整数零与 Ratio 值组合,除了第一个和结果向量通过引用分配 Ratio


I'm new with data.table, and I'm having an issue with this class.

I have a table (data1) with 2 columns : Couple and Ratio. Couple is the Key of the data.table.

I'm trying to modify a value in the table.

When I write the following code :

(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)

The error seems to have something to do with Keys but i cannot figure out what ?

Below is an example :

 >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

Thanks

解决方案

Judging from the first part of your question you want to actually do something like this:

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

This does a binary search for the value of cple in the data.table key and works then on this subset. An integer zero is combined with the Ratio values except the first and the resulting vector is assigned by reference to Ratio.

这篇关于修改R中data.table中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆