R从另一个矩阵中的信息创建一个二进制矩阵
R creating a binary matrix from information in another matrix
我有一个矩阵,指示哪一列的值应为 1。所有其他列的值应为 0。例如,
m = matrix(c(3,3,3,5,12,13),nrow = 3)
我应该如何有效地创建以下矩阵?
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[,1] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
[,2] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
[,3] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
谢谢
根据原始矩阵创建行 ID 和元素的矩阵 m1
创建一个用零填充的矩阵,其行数与原始矩阵相同,列数比原始矩阵中的最大元素多一个。
m1 <- matrix(c(rep(1:nrow(m), ncol(m)), as.vector(m)), ncol = 2)
mx <- matrix(0, nrow = 3, ncol = max(m) + 1)
mx[m1] <- 1
mx
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#> [1,] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
#> [2,] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
#> [3,] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
由 reprex package (v2.0.1)
于 2022-03-23 创建
您可以创建具有所需维度的 0 矩阵
out <- matrix(0, nrow = 3, ncol = 14)
然后 cbind
具有 c(m)
的行索引向量,即列位置
tmp <- cbind(seq_len(3), c(m))
tmp
是一个矩阵,您现在可以使用它来用 1
替换所需的位置
out[tmp] <- 1
out
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
# [1,] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
# [2,] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
# [3,] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
另一种可能效率较低的方法可能是这样
t(apply(m, 1, tabulate, nbins = 14))
我有一个矩阵,指示哪一列的值应为 1。所有其他列的值应为 0。例如,
m = matrix(c(3,3,3,5,12,13),nrow = 3)
我应该如何有效地创建以下矩阵?
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[,1] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
[,2] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
[,3] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
谢谢
根据原始矩阵创建行 ID 和元素的矩阵 m1
创建一个用零填充的矩阵,其行数与原始矩阵相同,列数比原始矩阵中的最大元素多一个。
m1 <- matrix(c(rep(1:nrow(m), ncol(m)), as.vector(m)), ncol = 2)
mx <- matrix(0, nrow = 3, ncol = max(m) + 1)
mx[m1] <- 1
mx
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#> [1,] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
#> [2,] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
#> [3,] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
由 reprex package (v2.0.1)
于 2022-03-23 创建您可以创建具有所需维度的 0 矩阵
out <- matrix(0, nrow = 3, ncol = 14)
然后 cbind
具有 c(m)
的行索引向量,即列位置
tmp <- cbind(seq_len(3), c(m))
tmp
是一个矩阵,您现在可以使用它来用 1
out[tmp] <- 1
out
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
# [1,] 0 0 1 0 1 0 0 0 0 0 0 0 0 0
# [2,] 0 0 1 0 0 0 0 0 0 0 0 1 0 0
# [3,] 0 0 1 0 0 0 0 0 0 0 0 0 1 0
另一种可能效率较低的方法可能是这样
t(apply(m, 1, tabulate, nbins = 14))