1.4 Replacing elements in a matrix

Replace 1 element.

A=matrix(1, 3, 3)
A[1,1]=2
A
     [,1] [,2] [,3]
[1,]    2    1    1
[2,]    1    1    1
[3,]    1    1    1

Replace a row with all 1s or a string of values

A=matrix(1, 3, 3)
A[1,]=2
A
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    1    1    1
[3,]    1    1    1
A[1,]=1:3
A
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    1    1
[3,]    1    1    1

Replace group of elements. This often does not work as one expects so be sure look at your matrix after trying something like this. Here I want to replace elements (1,3) and (3,1) with 2, but it didn’t work as I wanted.

A=matrix(1, 3, 3)
A[c(1,3),c(3,1)]=2
A
     [,1] [,2] [,3]
[1,]    2    1    2
[2,]    1    1    1
[3,]    2    1    2

How do I replace elements (1,1) and (3,3) with 2 then? It’s tedious. If you have a lot of elements to replace, you might want to use a for loop.

A=matrix(1, 3, 3)
A[1,3]=2
A[3,1]=2
A
     [,1] [,2] [,3]
[1,]    1    1    2
[2,]    1    1    1
[3,]    2    1    1