Reputation: 19803
I am attempting to assign a column by reference after I subsetted a data.table
and assigned the return value to another data.table
like so (toy example):
> x <- data.table(a=1:10, b=11:20, c=21:30)
> x
a b c
1: 1 11 21
2: 2 12 22
3: 3 13 23
4: 4 14 24
5: 5 15 25
6: 6 16 26
7: 7 17 27
8: 8 18 28
9: 9 19 29
10: 10 20 30
> y <- x[a==1 | a == 2, list(a,b,c)]
> y[,d:=a+b]
Error in `[.data.table`(y, , `:=`(d, a + b)) :
It appears that at some earlier point, names of this data.table have been reassigned. Please ensure to use setnames() rather than names<- or colnames<-. Otherwise, please report to datatable-help.
I don't exactly understand the issue: is it that the returned y
is simply a "view" into the same memory as x
and thus one should copy
x
before setting a column by reference?
Thanks
Upvotes: 1
Views: 2478
Reputation: 263352
Unable to reproduce the error with data.table 1.8.2 in R 2.15.1:
> x <- data.table(a=1:10, b=11:20, c=21:30); x
a b c
1: 1 11 21
2: 2 12 22
3: 3 13 23
4: 4 14 24
5: 5 15 25
6: 6 16 26
7: 7 17 27
8: 8 18 28
9: 9 19 29
10: 10 20 30
>
> y <- x[x$a==1 | x$a == 2, list(a,b,c)]
>
> y
a b c
1: 1 11 21
2: 2 12 22
> y[,d:=a+b]
a b c d
1: 1 11 21 12
2: 2 12 22 14
Upvotes: 3