# How to Juggle Dimensions and Replace Values in a Matrix in R

By default, R always tries to simplify the objects to the smallest number of dimensions possible when you use the brackets to extract values from an array. So, if you ask for only one column or row, R will make that a vector by dropping a dimension.

As with vectors, you can combine multiple numbers in the indices. If you want to drop the first and third rows of the matrix, you can do so like this:

> first.matrix[-c(1, 3), ] [1] 2 5 8 11

Wait a minute. . . . There’s only one index. R doesn’t return a matrix here — it returns a vector!

You can force R to keep all dimensions by using the extra argument drop from the indexing function. To get the second row returned as a matrix, you do the following:

> first.matrix[2, , drop=FALSE] [,1] [,2] [,3] [,4] [1,] 2 5 8 11

This seems like utter magic, but it’s not that difficult. You have three positions now between the brackets, all separated by commas. The first position is the row index. The second position is the column index. But then what?

Actually, the square brackets work like a function, and the row index and column index are arguments for the square brackets. Now you add an extra argument drop with the value FALSE. As you do with any other function, you separate the arguments by commas. Put all this together, and you have the code shown here.

Replacing values in a matrix is done in a very similar way to replacing values in a vector. To replace the value in the second row and third column of first.matrix with 4, you use the following code.

> first.matrix[3, 2] <- 4 > first.matrix [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 4 9 12

You also can change an entire row or column of values by not specifying the other dimension. Note that values are recycled, so to change the second row to the sequence 1, 3, 1, 3, you can simply do the following:

> first.matrix[2, ] <- c(1,3) > first.matrix [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 1 3 1 3 [3,] 3 4 9 12

You also can replace a subset of values within the matrix by another matrix. You don’t even have to specify the values as a matrix — a vector will do. Take a look at the result of the following code:

> first.matrix[1:2, 3:4] <- c(8,4,2,1) > first.matrix [,1] [,2] [,3] [,4] [1,] 1 4 8 2 [2,] 1 3 4 1 [3,] 3 4 9 12

Here you change the values in the first two rows and the last two columns to the numbers 8, 4, 2, and 1.

R reads and writes matrices column-wise by default. So, if you put a vector in a matrix or a subset of a matrix, it will be put in column-wise regardless of the method. If you want to do this row-wise, you first have to construct a matrix with the values using the argument byrow=TRUE. Then you use this matrix instead of the original vector to insert the values.