Replacing each row in a matrix

I have a matrix (mat1), say 100 rows and 100 columns; I want to create another matrix where each row will be the same as the first row in mat1 (except that I want to save the first col as the original values)

I managed to do this using a loop:

mat2 <- mat1 for(i in 1:nrow(mat1)) { mat2[i,2:ncol(mat2)] <- mat1[1,2:ncol(mat1)] } 

it works and gives the result that I expect; however, I would think that there should be a way to do this without a loop; I tried:

 mat2 <- mat1 mat2[c(2:100),2:ncol(mat2)] <- mat1[1,2:ncol(mat1)] 

Can someone point out my mistake ?!

Thanks,
Chris

+4
source share
3 answers

The problem is how R fills the columns matrix. Here is a simple example that illustrates this:

 mat1 <- matrix(1:9, ncol = 3) mat2 <- matrix(1:9, ncol = 3) mat2[-1, -1] <- mat1[1, -1] mat2 > mat2 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 4 4 [3,] 3 7 7 

mat1[1, -1] is a 4,7 vector, which you can see that R used to fill the bits of the mat2 column by columns. You need an operation with multiple lines.

One solution is to replicate the replacement vector as many times as needed:

 > mat2[-1, -1] <- rep(mat1[1, -1], each = nrow(mat1)-1) > mat2 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 4 7 [3,] 3 4 7 

This works because calling rep() replicates every value in the vector when we use the argument "each" instead of replicating (repeating) the vector:

 > rep(mat1[1, -1], each = nrow(mat1)-1) [1] 4 4 7 7 

The default behavior will also give the wrong answer:

 > rep(mat1[1, -1], nrow(mat1)-1) [1] 4 7 4 7 

In particular, the problem you see is also the way that R expands the arguments to an appropriate length for replacement. R actually and silently extends the replacement vector exactly as rep(mat1[1, -1], nrow(mat1)-1) , which, in combination with the column fill principle, gives the behavior you saw.

+7
source

Try

 mat2[c(2:nrow(mat2)), 2:ncol(mat2)] <- mat1[rep.int(1,nrow(mat1)-1),2:ncol(mat1)] 
+1
source

Another option ...

 n = 5 mat1 = matrix(sample(n^2, n^2), n, n) # use matrix with byrow to copy 1st row n times mat2 = matrix(rep(mat1[1, ], n), n, n, byrow = TRUE) # copy 1st column mat2[ , 1] = mat1[ , 1] mat1 mat2 
+1
source

All Articles