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

时间:2015-02-17 23:01:16

标签: r vectorization

替换矩阵条目的快捷方式:

   # 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[,]

1 个答案:

答案 0 :(得分:3)

您可以通过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