Duplicate Vector in Matrix by Row in R (Example Code)
In this article you’ll learn how to duplicate a vector in a matrix object in the R programming language.
Creation of Example Data
x <- letters[1:8] # Constructing an example vector x # [1] "a" "b" "c" "d" "e" "f" "g" "h" |
x <- letters[1:8] # Constructing an example vector x # [1] "a" "b" "c" "d" "e" "f" "g" "h"
Example: Duplicating a Vector as Rows in a Matrix
my_matrix <- t(replicate(5, x)) # Replicating vector multiple times my_matrix # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] # [1,] "a" "b" "c" "d" "e" "f" "g" "h" # [2,] "a" "b" "c" "d" "e" "f" "g" "h" # [3,] "a" "b" "c" "d" "e" "f" "g" "h" # [4,] "a" "b" "c" "d" "e" "f" "g" "h" # [5,] "a" "b" "c" "d" "e" "f" "g" "h" |
my_matrix <- t(replicate(5, x)) # Replicating vector multiple times my_matrix # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] # [1,] "a" "b" "c" "d" "e" "f" "g" "h" # [2,] "a" "b" "c" "d" "e" "f" "g" "h" # [3,] "a" "b" "c" "d" "e" "f" "g" "h" # [4,] "a" "b" "c" "d" "e" "f" "g" "h" # [5,] "a" "b" "c" "d" "e" "f" "g" "h"
Related Tutorials
Here, you can find some further resources on topics such as matrices, coding errors, and vectors: