Reputation: 1981
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
Reputation: 101034
We can use tcrossprod
to play a trick, where v^0
generates a vector of 1
s
> 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
Reputation: 1
create_mat<-function(V,r,c){
ans<- matrix(V, nrow = r, ncol = c, byrow =FALSE)
return ans
}
Upvotes: 0
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