更新data.table
此问题与1.8.0 及更高版本不再相关。从新闻文件:
现在允许在键中使用字符列,并且优先考虑因素。data.table() 和 setkey() 不再强制字符为因子。因素仍然得到支持。实现 FR#1493、FR#1224 和(部分)FR#951。
原始问题
我尝试加入两个data.tables。但是,连接的成功取决于我用来匹配 data.tables 的列的类。更准确地说,这些列似乎不应该具有类“字符”。我不太明白原因,但我确定我在这里遗漏了一些明显的东西。因此,非常感谢您的帮助。
这是一个例子:
#Objective: Select all rows from DT for which Region=="US", Year >= 5 & Year<=8, Cat="A"
library(data.table)
#Set-up data.table DT
DT <- data.table(Year=1:20, value=rnorm(20), Region=c(rep("US", 10), rep("EU", 10)), Cat=c(rep("A", 7), rep("B", 7), rep("C", 6)))
setkey(DT, Region, Cat, Year)
#Set-up data.table int_DT to join with DT
years <- 5:8
df <- data.frame(Region=c("US", "EU"), Categ=c("A", "B"))
int_DT <- J(cbind(df[1, ], years))
#Join them: Works like a charm!
DT[int_DT]
#Let's assume that for any reason the columns in df are of class "character"
df$Region <- as.character(df$Region)
df$Categ <- as.character(df$Categ)
#Rebuild int_DT
int_DT <- J(cbind(df[1, ], years))
DT[int_DT]
#Error in `[.data.table`(DT, int_DT) :
# unsorted column Region of i is not internally type integer.
#OK, maybe the problem is that the column classes in DT are factors, so change those:
DT[, Cat:=as.character(Cat)]
DT[, Region:=as.character(Region)]
DT[int_DT]
#Error in `[.data.table`(DT, int_DT) :
# When i is a data.table, x must be sorted to avoid a vector scan of x per row of i
还是不行。为什么?有什么限制?我想念什么?附加信息:我在平台:x86_64-pc-linux-gnu(64 位)上使用 data.table 1.6.6 和 R 版本 2.13.2(2011-09-30)。