好吧,这有点奇怪...似乎通过使用 := 运算符在 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 := 运算符的错误,还是预期的行为?
谢谢!