Search code examples
rgetassign

assign dimnames to a list of matrices in R


I have a new list of matrices for which their (missing) dimnames have to be replaced by the dimnames of a previous list of matrices. I would need to do that through a loop (for loop , apply, ...) since the number of matrices per list is variable.

Example data:

new_list <- list(
    matrix1=matrix(
        sample(20,24,T),
        6
    ),
    matrix2=matrix(
        sample(20,24,T),
        6
    ),
    matrix3=matrix(
        sample(20,24,T),
        6
    )
)

old_list <- list(
    matrix1=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 1:4))
    ),
    matrix2=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 5:8))
    ),
    matrix3=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 9:12))
    )
)

new_list
$matrix1
     [,1] [,2] [,3] [,4]
[1,]    2   18    2    5
[2,]   17   20   12    4
[3,]    5    9   18    4
[4,]   15   13    5   20
[5,]    7   13   10   13
[6,]   14    7    6   12

$matrix2
     [,1] [,2] [,3] [,4]
[1,]   16    6   16    7
[2,]   17   10    6   13
[3,]    9    9   18   14
[4,]    7    7    7   19
[5,]   19   20   13    9
[6,]   12   20   13   18

$matrix3
     [,1] [,2] [,3] [,4]
[1,]    3   14   15   10
[2,]    9   18   15   15
[3,]    4   13   20    2
[4,]   15   10    2    6
[5,]   15    9    1    1
[6,]    5   20    9   18

old_list
$matrix1
      Col_1 Col_2 Col_3 Col_4
Row_1     2     4     3     5
Row_2     6     8     1     3
Row_3     5     1     9    10
Row_4     2     8     8     7
Row_5     5     8     8     8
Row_6    10     5     9     8

$matrix2
      Col_5 Col_6 Col_7 Col_8
Row_1     9     4     6     4
Row_2     1     1     4     1
Row_3     5     6     1     7
Row_4     9    10     2    10
Row_5     4     9     1     6
Row_6    10     2     9     7

$matrix3
      Col_9 Col_10 Col_11 Col_12
Row_1     2      8     10      2
Row_2     4     10      3      3
Row_3     8      8      6      5
Row_4     2      8      8      3
Row_5     4      7     10      8
Row_6     9      9      9      2

Manually it would look like this:

dimnames(new_list$matrix1) = dimnames(old_list$matrix1)
dimnames(new_list$matrix2) = dimnames(old_list$matrix2)
dimnames(new_list$matrix3) = dimnames(old_list$matrix3)

I tried the following but it returns an error:

for(i in names(old_list)){
   assign("My_NewList", paste0("new_list$", i))
   assign("My_OldList", paste0("old_list$", i))

   dimnames(get("My_NewList")) = dimnames(get("My_OldList"))
}

Error in dimnames(get("My_NNewList")) = dimnames(get("My_OldList")) :
  target of assignment expands to non-language object

Solution

  • We can use Map to do the assignment

    Map(function(x, y) {dimnames(x) <- dimnames(y); x}, new_list, old_list)