我有一个data.table,我试图设置某些元素。
mydt <- as.data.table(data.frame(a=letters[1:26],b=c(1:26)))
setkey(mydt, a)
我可以看到我可以使用键值过滤条目。
> mydt[c('b','f','g'),b]
[1] 2 6 7
> mydt[c('b','f','g')]$b
[1] 2 6 7
但是,当我尝试在b
列中设置一些值时,我得到:
> mydt[c('b','f','g')]$b = c(45,67,89)
Error in `[.data.table`(`*tmp*`, c("b", "f", "g")) :
When i is a data.table (or character vector), the columns to join by must be specified either using 'on=' argument (see ?data.table) or by keying x (i.e. sorted, and, marked as sorted, see ?setkey). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.
> mydt[c('b','f','g'),b] = c(45,67,89)
Error in `[.data.table`(x, i, which = TRUE) :
When i is a data.table (or character vector), the columns to join by must be specified either using 'on=' argument (see ?data.table) or by keying x (i.e. sorted, and, marked as sorted, see ?setkey). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.
错误消息对我来说似乎很神秘。
答案 0 :(得分:1)
我们需要使用:=
mydt[c('b','f','g'), b := c(45L,67L,89L)]
确保列类型匹配为c(45, 67, 89)
为numeric
b
类为integer
。一种选择是添加L
作为后缀或使用as.integer(c(45, 67, 89))