我正在尝试加入两个 data.tables,就像我用 merge() 和 all=TRUE 加入数据帧一样,如下所示:
> x = data.frame(index = 1:10)
> y = data.frame(index = c(2,4,6), weight = c(0.2, 0.3, 0.5))
> x
index
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
> y
index weight
1 2 0.2
2 4 0.3
3 6 0.5
> merge(x,y, all=TRUE)
index weight
1 1 NA
2 2 0.2
3 3 NA
4 4 0.3
5 5 NA
6 6 0.5
7 7 NA
8 8 NA
9 9 NA
10 10 NA
我有两个数据表,matched.weights 和 casted,这是 cast 函数的结果。它们的键都是“索引”。
> matched.weights
index
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
First 10 rows of 14708 printed.
> casted
index 1 2
[1,] 10002 0.0049024578 3.057794e-03
[2,] 10129 0.0011064567 8.481497e-04
[3,] 10171 0.0012964050 5.540875e-03
[4,] 10177 0.0008181397 6.981567e-04
[5,] 10187 0.0060350971 2.156695e-03
[6,] 1022 0.0011320117 8.665125e-04
[7,] 10250 0.0047892924 7.725221e-03
[8,] 10262 0.0044724898 8.787161e-06
[9,] 10286 0.0016650838 7.162887e-05
[10,] 10299 0.0015840791 5.578903e-03
First 10 rows of 305 printed.
当我尝试合并它们时出现此错误:
> merge(matched.weights, casted, all=TRUE)
Error in setcolorder(dt, c(setdiff(names(dt), end), end)) :
neworder is length 5 but x has 3 columns.
当我使用 data.table 语法时,它会用 NA 替换数据条目:
> merged = casted[matched.weights]
> merged
index X1 X2
[1,] 1 NA NA
[2,] 2 NA NA
[3,] 3 NA NA
[4,] 4 NA NA
[5,] 5 NA NA
[6,] 6 NA NA
[7,] 7 NA NA
[8,] 8 NA NA
[9,] 9 NA NA
[10,] 10 NA NA
First 10 rows of 14708 printed.
> merged[10002]
index X1 X2
[1,] 10002 NA NA
> sum(merged[[2]], na.rm=T)
[1] 0
谁能向我解释发生了什么事?