R:给定一组索引更新矩阵

时间:2014-03-09 16:44:46

标签: r matrix

我有一个矩阵(初始化为零)和一组索引。如果索引中的第i个值是j,那么我想将矩阵的第(j,i)个条目设置为1.

例如:

> m = matrix(0, 10, 7)

> indices
[1]  2  9  3  4  5  1 10

结果应该是

> result
      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    0    0    0    0    1    0
 [2,]    1    0    0    0    0    0    0
 [3,]    0    0    1    0    0    0    0
 [4,]    0    0    0    1    0    0    0
 [5,]    0    0    0    0    1    0    0
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    1    0    0    0    0    0
[10,]    0    0    0    0    0    0    1

我稍微询问了一点related question,它使用的是矢量而不是矩阵。这个问题是否有类似的简单解决方案?

2 个答案:

答案 0 :(得分:1)

## OP's example data
m = matrix(0, 10, 7)
j <- c(2,  9,  3,  4,  5,  1, 10)

## Construct a two column matrix of indices (1st column w. rows & 2nd w. columns)
ij <- cbind(j, seq_along(j))
## Use it to subassign into the matrix
m[ij] <- 1
m
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#  [1,]    0    0    0    0    0    1    0
#  [2,]    1    0    0    0    0    0    0
#  [3,]    0    0    1    0    0    0    0
#  [4,]    0    0    0    1    0    0    0
#  [5,]    0    0    0    0    1    0    0
#  [6,]    0    0    0    0    0    0    0
#  [7,]    0    0    0    0    0    0    0
#  [8,]    0    0    0    0    0    0    0
#  [9,]    0    1    0    0    0    0    0
# [10,]    0    0    0    0    0    0    1

答案 1 :(得分:1)

对于记录,使用sapply

可以轻松调整链接问题中的答案以适应这种情况
indices <- c(2,  9,  3,  4,  5,  1, 10)
sapply(indices, tabulate, nbins = 10)
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#  [1,]    0    0    0    0    0    1    0
#  [2,]    1    0    0    0    0    0    0
#  [3,]    0    0    1    0    0    0    0
#  [4,]    0    0    0    1    0    0    0
#  [5,]    0    0    0    0    1    0    0
#  [6,]    0    0    0    0    0    0    0
#  [7,]    0    0    0    0    0    0    0
#  [8,]    0    0    0    0    0    0    0
#  [9,]    0    1    0    0    0    0    0
# [10,]    0    0    0    0    0    0    1

对于小型数据集,您可能没有注意到性能差异,但Josh的答案(使用矩阵索引)肯定会更快 ,即使您在此处更改我的答案以使用vapply而不是sapply