[datatable-help] Inconsistent [<- behavior

Matthew Dowle mdowle at mdowle.plus.com
Tue Sep 13 10:26:53 CEST 2011


Hi. Thanks for reporting. The 'correct' ways that work using := are the best 
ways going forward. But agreed, will fix so that all ways work.

"Leon Baum" <leonbaum2 at gmail.com> wrote in message 
news:87sjo1nwnt.fsf at gmail.com...
>
> Hello,
>
> I believe that all of the following should result in the same data.table
> (ignoring different orderings), but some of them give me errors:
>
>
>> dt <- data.table(x=letters[1:2], y=rnorm(4))
>> dt[c(1, 3), ]$y <- 0
>> dt
>     x         y
> [1,] a  0.000000
> [2,] b -1.645834
> [3,] a  0.000000
> [4,] b -1.311856
> # correct
>
>> dt <- data.table(x=letters[1:2], y=rnorm(4))
>> dt[x == "a", ]$y <- 0
> Error in `[<-.data.frame`(x, i, j, value) : object 'x' not found
> # bad
>
>> dt <- data.table(x=letters[1:2], y=rnorm(4))
>> dt[x == "a", y:=0]
>     x          y
> [1,] a  0.0000000
> [2,] b -0.1028541
> [3,] a  0.0000000
> [4,] b  0.3569112
> # correct
>
>> dt <- data.table(x=letters[1:2], y=rnorm(4), key="x")
>> dt["a", ]$y <- 0
> Warning messages:
> 1: In `[<-.data.frame`(x, i, j, value) :
>  replacement element 1 has 2 rows to replace 1 rows
> 2: In `[<-.data.frame`(x, i, j, value) :
>  replacement element 2 has 2 rows to replace 1 rows
>> dt
>     x          y
> [1,] a -0.4444458
> [2,] a -2.1279203
> [3,] b -1.9065767
> [4,] b  0.5903236
> [5,] a  0.0000000
> # bad
>
>> dt <- data.table(x=letters[1:2], y=rnorm(4), key="x")
>> dt["a", y:=0]
>     x           y
> [1,] a  0.00000000
> [2,] a  0.00000000
> [3,] b  1.05028739
> [4,] b -0.02362426
> # correct
>
> I am using R-2.13.1 and data.table 1.6.6.
>
> -Leon 





More information about the datatable-help mailing list