我仍然困惑于data.table J的行为。
> DT = data.table(A=7:3,B=letters[5:1])
> DT
A B
1: 7 e
2: 6 d
3: 5 c
4: 4 b
5: 3 a
> setkey(DT, A, B)
> DT[J(7,"e")]
A B
1: 7 e
> DT[J(7,"f")]
A B
1: 7 f # <- there is no such line in DT
但是在DT中没有这样的行。为什么会得到这个结果?
我仍然困惑于data.table J的行为。
> DT = data.table(A=7:3,B=letters[5:1])
> DT
A B
1: 7 e
2: 6 d
3: 5 c
4: 4 b
5: 3 a
> setkey(DT, A, B)
> DT[J(7,"e")]
A B
1: 7 e
> DT[J(7,"f")]
A B
1: 7 f # <- there is no such line in DT
数据表 J(7, 'f')
实际上是一个单行的 data.table
,你要将其与自己的 data.table
进行连接。当你调用 x[i]
时,你正在查看 i
中的每一行,并在 x
中找到所有匹配项。默认情况下,对于在 i
中没有匹配项的行,会给出 NA
,如果向 DT
添加另一列,则更容易看到这一点:
DT <- data.table(A=7:3,B=letters[5:1],C=letters[1:5])
setkey(DT, A, B)
DT[J(7,"f")]
# A B C
# 1: 7 f NA
J
中唯一没有与DT
匹配的行。为了防止data.table
报告不匹配,您可以使用nomatch=0
。DT[J(7,"f"), nomatch=0]
# Empty data.table (0 rows) of 3 cols: A,B,C
DT[, C:=paste0(A, B)]
DT[J(7,"e")]
### A B C
### 1: 7 e 7e
DT[J(7,"f")]
### A B C
### 1: 7 f NA
这与没有使用 J
时的行为相同:
setkey(DT, B)
DT["a"]
### B A C
### 1: a 3 3a
DT["A"]
### B A C
### 1: A NA NA
nomatch
参数来更改此行为。DT[J(7,"f"), nomatch=0L]
### Empty data.table (0 rows) of 3 cols: A,B,C
nomatch
参数的解释,以及如何使用它的说明? - BenBarnes