我试图理解当 R 中的 data.table 中有重复键时 J() 查找的逻辑。
这是我尝试过的一个小实验:
library(data.table)
options(stringsAsFactors = FALSE)
x <- data.table(keyVar = c("a", "b", "c", "c"),
value = c( 1, 2, 3, 4))
setkey(x, keyVar)
y1 <- data.frame(name = c("d", "c", "a"))
x[J(y1$name), ]
## OK
y2 <- data.frame(name = c("d", "c", "a", "b"))
x[J(y2$name), ]
## Error: see below
x2 <- data.table(keyVar = c("a", "b", "c"),
value = c( 1, 2, 3))
setkey(x2, keyVar)
x2[J(y2$name), ]
## OK
我收到的错误消息是:
Error in vecseq(f__, len__, if (allow.cartesian) NULL else as.integer(max(nrow(x), :
Join results in 5 rows; more than 4 = max(nrow(x),nrow(i)). Check for duplicate key
values in i, each of which join to the same group in x over and over again. If that's
ok, try including `j` and dropping `by` (by-without-by) so that j runs for each group
to avoid the large allocation. If you are sure you wish to proceed, rerun with
allow.cartesian=TRUE. Otherwise, please search for this error message in the FAQ, Wiki,
Stack Overflow and datatable-help for advice.
我实在不明白这一点。我知道我应该避免在查找函数中出现重复的键,我只是想获得一些见解,这样我将来就不会犯任何错误。
非常感谢您的帮助。这是一个很棒的工具。