Changing a value in a data table in R

I am new to data.table and I have a problem with this class.

I have a table (data1) with two columns: pair and coefficient. A pair is the key of a data table.

I am trying to change a value in a 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 not the same as the above code) 

The error seems to be related to the keys, but I can’t understand what?

The following 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 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; ie 'replace' column), or coerce RHS to 'integer' (eg 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

+4
source share
2 answers

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

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

This performs a binary search for the cple value in the cple file and then works on this subset. The integer is combined with the Ratio values ​​except the first, and the resulting vector is assigned by the Ratio reference.

+4
source

you should not use $ with data.table when ASSIGN data.table is a child of data.frame , but it is much better since it can be updated by reference without copies. Each time you try to assign with $ , for example data1$Ratio[1]<-2 , it copies the whole table. You should look at the vignette and especially at the update := . In your case, `data1 [Pair == 'a', Ratio: = c (0L, Ratio [-1])] is what you want.

You might want to read this very good post .

+5
source

All Articles