R: How to run a function/calculation on two lists

2020-05-09 06:04发布

I want to run a function (in this case just a multiplication) on two list based on their names. Here some example 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 matrices for different products (listnames=111,112) and List B (below) has YEARLY values for the same products, names are composed of product and year and separated by "." (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)})

Until now I run my multiplication using mapply:

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

which in this case delivers a wright result. However, loosing the names of B which are the import ones for me. Another problem is that B has more objects then A, therefore I would like to run a name match within the calculation: names in A e.g. 111, should match names in B 111.2000 and 111.2001. Any ideas?

Note: that the productnames could have also 2 digits and not only 3. So I need a match using the digits in front of the "." Thanks

标签: r list mapply
1条回答
叛逆
2楼-- · 2020-05-09 06:38

You can use Map to loop over B and B names, this will also keep up the names:

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
查看更多
登录 后发表回答