将数据从一个 data.table 填充到另一个

Populating data from one data.table to another

我有一个距离矩阵(如 data.table)显示多个项目之间的成对距离,但并非所有项目都在矩阵中。我需要创建一个更大的 data.table 来填充所有缺失的项目。我可以很容易地用矩阵做到这一点:

items=c("a", "b", "c", "d")
small_matrix=matrix(c(0, 1, 2, 3), nrow=2, ncol=2, 
      dimnames=list(c("a", "b"), c("a", "b")))

# create zero matrix of the right size
full_matrix <- matrix(0, ncol=length(items), nrow=length(items),
      dimnames=list(items, items))

# populate items from the small matrix
full_matrix[rownames(small_matrix), colnames(small_matrix)] <- small_matrix
full_matrix
#   a b c d
# a 0 2 0 0
# b 1 3 0 0
# c 0 0 0 0
# d 0 0 0 0

data.table 中的等价物是什么?我可以在 small_DT 中创建一个 'id' 列并将其用作键,但我不确定如何覆盖 full_DT 中具有相同 id/column 对的项。

假设你有这两个 data.table:

dt1 = as.data.table(small_matrix)

#   a b
#1: 0 2
#2: 1 3

dt2 = as.data.table(full_matrix)

#   a b c d
#1: 0 0 0 0
#2: 0 0 0 0
#3: 0 0 0 0
#4: 0 0 0 0

您不能像 data.framematrix 那样操作,例如:

dt2[rownames(full_matrix) %in% rownames(small_matrix), names(dt1), with=F] <- dt1

此代码会引发错误,因为要影响新值,您需要使用 := 运算符:

dt2[rownames(full_matrix) %in% rownames(small_matrix), names(dt1):=dt1][]

#   a b c d
#1: 0 2 0 0
#2: 1 3 0 0
#3: 0 0 0 0
#4: 0 0 0 0

让我们转换为 data.table 并将行名称保留为额外的列:

dts = as.data.table(small_matrix, keep = T)
#   rn a b
#1:  a 0 2
#2:  b 1 3
dtf = as.data.table(full_matrix, keep = T)
#   rn a b c d
#1:  a 0 0 0 0
#2:  b 0 0 0 0
#3:  c 0 0 0 0
#4:  d 0 0 0 0

现在只需连接行,假设小矩阵始终是一个子集,您可以执行以下操作:

dtf[dts, names(dts) := dts, on = 'rn']
dtf
#   rn a b c d
#1:  a 0 2 0 0
#2:  b 1 3 0 0
#3:  c 0 0 0 0
#4:  d 0 0 0 0

以上假定版本为 1.9.5+。否则您需要先设置密钥。