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

醉酒当歌 提交于 2019-12-31 05:21:05

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/33800893/r-how-to-run-a-function-calculation-on-two-lists-based-on-their-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!