Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R duplicate a matrix several times and then bind by rows together

I have the following matrix

FI1  FI2 YI1 YI2 BAL1 BAL2 GRO1 GRO2  EQ1  EQ2
1 0.22 0.15 0.1 0.1 0.05 0.05 0.05 0.05 0.05 0.05
2 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
3 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
4 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
5 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
6 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00

Now I would like to have this matrix duplicated 10 times and put in a matrix such that it looks like this (I just show it 2 times here)

FI1  FI2 YI1 YI2 BAL1 BAL2 GRO1 GRO2  EQ1  EQ2
1 0.22 0.15 0.1 0.1 0.05 0.05 0.05 0.05 0.05 0.05
2 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
3 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
4 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
5 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
6 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
1 0.22 0.15 0.1 0.1 0.05 0.05 0.05 0.05 0.05 0.05
2 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
3 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
4 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
5 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00
6 0.22 0.00 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.00

Can somebody propose me a simple way to accomplish this? Thanks Andreas

like image 277
user2157086 Avatar asked Oct 25 '13 12:10

user2157086


People also ask

How do you repeat a matrix in R?

The matrix can be created by using matrix function in R and if we want to create a matrix by replicating a vector then we just need to focus on the replication. For example, if we have a vector V and we want to create matrix by replicating V two times then the matrix can be created as matrix(replicate(2,V),nrow=2).

How do I duplicate rows n times in R?

The way to repeat rows in R is by using the REP() function. The REP() function is a generic function that replicates the value of x one or more times and it has two mandatory arguments: x: A vector.

How does Rbind work in R?

rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows. deparse. level: This value determines how the column names generated. The default value of deparse.

How do you repeat a column in R?

First of all, create a data frame. Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.


2 Answers

The mathematical way to do this is to take the Kronecker product of the matrix with a vector of ones.

mX = matrix(rnorm(100), 10, 10)
mX %x% rep(1, numTimesToRepeat)
like image 79
tchakravarty Avatar answered Oct 24 '22 12:10

tchakravarty


Here's another way:

do.call(rbind, replicate(10, m, simplify=FALSE)) # where m is your matrix
like image 42
Matthew Plourde Avatar answered Oct 24 '22 13:10

Matthew Plourde