rose
rose

Reputation: 1981

Create a matrix from a vector in R

I have a vector v, and I would like to create the following matrix. How can I do this in R?

      v = c(1, 2, 3, 4)

      > m = matrix(c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,4), nrow=4)
      > m
           [,1] [,2] [,3] [,4]
     [1,]    1    2    3    4
     [2,]    1    2    3    4
     [3,]    1    2    3    4
     [4,]    1    2    3    4

Upvotes: 2

Views: 385

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

We can use tcrossprod to play a trick, where v^0 generates a vector of 1s

> tcrossprod(v^0,v)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
[3,]    1    2    3    4
[4,]    1    2    3    4

Upvotes: 0

anitha devi P
anitha devi P

Reputation: 1

create_mat<-function(V,r,c){
   ans<- matrix(V, nrow = r, ncol = c, byrow =FALSE)
   return ans
}

Upvotes: 0

sgibb
sgibb

Reputation: 25726

See ?matrix and the nrow, ncol, byrow arguments:

matrix(v, nrow=4, ncol=4, byrow=TRUE)
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    3    4
#[2,]    1    2    3    4
#[3,]    1    2    3    4
#[4,]    1    2    3    4

Upvotes: 4

Related Questions