Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate vector into matrix r

Tags:

Wondering how to duplicate a vector into a matrix in R. For example

v = 1:10 dup = duplicate(V,2) 

where dup looks like rbind(1:10,1:10). Thanks

like image 579
Michael Avatar asked Feb 17 '13 23:02

Michael


People also ask

How do you repeat a vector in 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 a vector in R?

There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.

How do you convert a vector to a matrix?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.

How do you assign a matrix in R?

To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.


2 Answers

I think you're looking for replicate.

t(replicate(2, v)) 
like image 183
Arun Avatar answered Oct 11 '22 11:10

Arun


Alternatively:

matrix(v, nrow=2, ncol=length(v), byrow=TRUE) 
like image 24
thelatemail Avatar answered Oct 11 '22 13:10

thelatemail