Search notes:

R: Create a matrix from a vector

vec <- c(   1,   2,   3,   4,
           11,  22,  33,  44,
          111, 222, 333, 444)

matrix(vec)
#
#       [,1]
#  [1,]    1
#  [2,]    2
#  [3,]    3
#  [4,]    4
#  [5,]   11
#  [6,]   22
#  [7,]   33
#  [8,]   44
#  [9,]  111
# [10,]  222
# [11,]  333
# [12,]  444

matrix(vec, nrow=3)
#
#      [,1] [,2] [,3] [,4]
# [1,]    1    4   33  222
# [2,]    2   11   44  333
# [3,]    3   22  111  444

matrix(vec, nrow=3, byrow = TRUE)
#
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]   11   22   33   44
# [3,]  111  222  333  444
Github repository about-r, path: /data-structures/matrix/vector-to-matrix.R

See also

vector, matrix

Index