R: How to run a function / calculation in two lists based on their names?

I want to run a function (in this case, just multiplication) in two lists based on their names. Here are some examples of data showing my structure:

A <- list("111"=matrix(sample(1:10,9), nrow=3, ncol=3),
          "112"=matrix(sample(1:10,9), nrow=3, ncol=3))
names <- list(c("A", "B", "C"), c("A", "B", "C"))
A <- lapply(ProdValues, function (x) {dimnames(x) <- names; return(x)})

List A has values ​​in the matrices for different products (listnames = 111,112), and in list B (below) there are YEARLY values ​​for the same products, the names consist of the product and the year and are separated by the symbol ".". (e.g. 111,2000):

B <- list("111.2000"=matrix(sample(1:10,9), nrow=3, ncol=3),
          "112.2000"=matrix(sample(1:10,9), nrow=3, ncol=3),
          "111.2001"=matrix(sample(1:10,9), nrow=3, ncol=3),
          "112.2001"=matrix(sample(1:10,9), nrow=3, ncol=3))
names <- list(c("A", "B", "C"), c("A", "B", "C"))
B <- lapply(ProdYears, function (x) {dimnames(x) <- names; return(x)})

So far I am running my multiplication using mapply:

fun <- function(A, B) {
  calc= A*B
  return(calc)
}
mapply(fun, A, B, SIMPLIFY = FALSE)

. , B, . , B , A, : A, . 111, B 111.2000 111.2001. ?

: 2 , 3. , ".".

0
1

Map B B, :

Map(function(x,y) A[[y]]*x, B, gsub('\\..*','',names(B)))

#$`111.2000`
#     [,1] [,2] [,3]
#[1,]   36   18   54
#[2,]   16   25    3
#[3,]   56   10   20

#$`112.2000`
#     [,1] [,2] [,3]
#[1,]   18   10   40
#[2,]   35   18   60
#[3,]    3   63   16

#$`111.2001`
#     [,1] [,2] [,3]
#[1,]   81   30   18
#[2,]   56   25    1
#[3,]   28   20   16

#$`112.2001`
#     [,1] [,2] [,3]
#[1,]   36   30   72
#[2,]   30   30    6
#[3,]    5   56    4
+2

Source: https://habr.com/ru/post/1618573/


All Articles