Qbik
Qbik

Reputation: 6147

Fast substitution of chosen entries of matrix in R

Fast way for substitution of matrix entries :

   # 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

It should be possible, as we can treat matrix as vector and use vector notation on matrix object matrix[] instead of matrix notation matrix[,]

Upvotes: 2

Views: 50

Answers (1)

Marat Talipov
Marat Talipov

Reputation: 13304

You can achieve it by m[matrix(c(1,2,1,2),ncol=2)] <- 1

The same thing in the expanded form:

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

Upvotes: 3

Related Questions