Aesler
Aesler

Reputation: 181

Replacing matrix values with vector values

matrix:
      [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

vector = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l")

How can I replace the values such that I get:

      [,1] [,2] [,3]
[1,]    a    e    i
[2,]    b    f    j
[3,]    c    g    k
[4,]    d    h    l

NB: I have used generic vectors but I will be doing this with much bigger varied data sets so I am not after something like:

matrix(letters[1:12],4,3)

Upvotes: 0

Views: 106

Answers (2)

cdeterman
cdeterman

Reputation: 19950

If you matrix does only contain integers like that then you can do the following

mat <- matrix(sample(seq(12), 12), nrow = 4)
vec <- letters[1:12]

mat[] <- vec[mat[]]

Upvotes: 1

kgui
kgui

Reputation: 4165

Since you're not conserving any of the original values of the matrix, the following would work

> matrix_name <- matrix(data = your_vector, 
                       nrow = 4,
                       ncol = 3,
                       byrow = FALSE)

Upvotes: 0

Related Questions