Reputation: 25560
I have row f
. I want create matrix R
such that every row of it is equal f
.
What is the most efficient way to do it in R?
Upvotes: 7
Views: 5908
Reputation: 263342
R <- matrix(f, 1)[rep(1,n), ]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 2 3 4 5
[3,] 1 2 3 4 5
[4,] 1 2 3 4 5
[5,] 1 2 3 4 5
Or even more compact:
R <- rbind(f)[rep(1,n), ]
[,1] [,2] [,3] [,4] [,5]
f 1 2 3 4 5
f 1 2 3 4 5
f 1 2 3 4 5
f 1 2 3 4 5
f 1 2 3 4 5
Note that rownames of matrices do not need to be unique, unlike the case with data.frames.
Upvotes: 5
Reputation: 49640
Here is one possibility:
mymat <- do.call( rbind, rep(list(f), 10) )
Upvotes: 3
Reputation: 4795
with a row
f=c(1,22,33,44,55,66)
get its length
lf=length(f)
Then make the matrix
R=matrix(rep(f,lf),
ncol=lf,
byrow=T)
Gives:
R
[,1] [,2] [,3] [,4] [,5]
[1,] 1 33 44 55 66
[2,] 1 33 44 55 66
[3,] 1 33 44 55 66
[4,] 1 33 44 55 66
[5,] 1 33 44 55 66
Upvotes: 9