Albert Masclans Albert Masclans - 1 month ago 9
R Question

Getting a matrix of values from a Matrix with names and list with values

I have a character matrix M1 with names and a named list L1 with values.

I want to create a matrix M2 with values, the same size as M1. For each cell in M2, there should be the value that in L1 corresponds to the name in M1. Cells in which M1's name is not in L1, M2 should be NA.

I tried to do so but hadn't managed to.

Here's an example of what I'd want to do.

>M1
[,1] [,2] [,3] [,4]
[1,] "n1" "n4" "n7" "n10"
[2,] "n2" "n5" "n8" "n11"
[3,] "n3" "n6" "n9" "n12"

> L1
$n1
[1] 1

$n2
[1] 2

$n8
[1] 3

$n25
[1] 4


From there M2 should end up being:

> M2
[,1] [,2] [,3] [,4]
[1,] 1 NA NA NA
[2,] 2 NA 3 NA
[3,] NA NA NA NA


Reproducible Examples,

dput(m1)
structure(c("n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9",
"n10", "n11", "n12"), .Dim = 3:4)

dput(L1)
structure(list(n1 = 1, n2 = 2, n8 = 3, n25 = 4), .Names = c("n1",
"n2", "n8", "n25"))

Answer

One way is to unlist L1 and match the names with each element of the matrix

apply(m1, 1:2, function(i) unlist(L1)[match(i, names(L1))])

#      [,1] [,2] [,3] [,4]
#[1,]    1   NA   NA   NA
#[2,]    2   NA    3   NA
#[3,]   NA   NA   NA   NA