在 R 中快速替换矩阵的选定条目

Fast substitution of chosen entries of matrix in R

替换矩阵条目的快速方法:

   # I would like to set values of (1,1) and (2,2) entries of `m` matrix to 3,  
   # obviously below code 
   # replaces also values in (1,2) and (2,1) also, is the is way to replace 
   # entries in proper way without using for()
        m <- matrix(0,5,3)
        m[1:2,1:2] <- 1
#>m
#     [,1] [,2] [,3]
#[1,]    1    1    0
#[2,]    1    1    0
#[3,]    0    0    0
#[4,]    0    0    0
#[5,]    0    0    0

这应该是可能的,因为我们可以将 matrix 视为 vector 并在矩阵对象 matrix[] 上使用矢量符号而不是矩阵符号 matrix[,]

你可以通过m[matrix(c(1,2,1,2),ncol=2)] <- 1

实现

相同的扩展形式:

m.subset <- matrix(c(1,2,1,2),ncol=2)
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    2

m[m.subset] <- 1
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    0
#[4,]    0    0    0
#[5,]    0    0    0