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
You can use
Map
to loop over B and B names, this will also keep up the names: