これは少し奇妙です... := 演算子を使用して data.table に新しい列を作成すると、以前に割り当てられた変数 (colnames を使用して作成) が静かに変更されるようです。
これは予想される動作ですか?そうでない場合、何が問題なのですか?
# Lets make a simple data table
require(data.table)
dt <- data.table(fruit=c("apple","banana","cherry"),quantity=c(5,8,23))
dt
fruit quantity
1: apple 5
2: banana 8
3: cherry 23
# and assign the column names to a variable
colsdt <- colnames(dt)
str(colsdt)
chr [1:2] "fruit" "quantity"
# Now let's add a column to the data table using the := operator
dt[,double_quantity:=quantity*2]
dt
fruit quantity double_quantity
1: apple 5 10
2: banana 8 16
3: cherry 23 46
# ... and WITHOUT explicitly changing 'colsdt', let's take another look:
str(colsdt)
chr [1:3] "fruit" "quantity" "double_quantity"
# ... colsdt has been silently updated!
比較のために、 data.frame メソッドを介して新しい列を追加しても同じ問題があるかどうかを確認します。それはしません:
dt$triple_quantity=dt$quantity*3
dt
fruit quantity double_quantity triple_quantity
1: apple 5 10 15
2: banana 8 16 24
3: cherry 23 46 69
# ... again I make no explicit changes to colsdt, so let's take a look:
str(colsdt)
chr [1:3] "fruit" "quantity" "double_quantity"
# ... and this time it is NOT silently updated
これは data.table := 演算子のバグですか、それとも予想される動作ですか?
ありがとう!