[datatable-help] Inconsistent [<- behavior

Leon Baum leonbaum2 at gmail.com
Tue Sep 13 01:55:18 CEST 2011


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