1.4 Replacing elements in a matrix
Replace 1 element.
=matrix(1, 3, 3)
A1,1]=2
A[ 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
=matrix(1, 3, 3)
A1,]=2
A[ A
[,1] [,2] [,3]
[1,] 2 2 2
[2,] 1 1 1
[3,] 1 1 1
1,]=1:3
A[ 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.
=matrix(1, 3, 3)
Ac(1,3),c(3,1)]=2
A[ 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.
=matrix(1, 3, 3)
A1,3]=2
A[3,1]=2
A[ A
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 1 1 1
[3,] 2 1 1