R:如何根据两个列表的名称在两个列表上运行函数/计算? [英] R: How to run a function/calculation on two lists based on their names?

查看:95
本文介绍了R:如何根据两个列表的名称在两个列表上运行函数/计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据它们的名称在两个列表上运行一个函数(在这种情况下,只是一个乘法).这里有一些示例数据显示了我的结构:

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)})

列表A具有不同产品的矩阵值(列表名称= 111,112),列表B(以下)具有相同产品的YEARLY值,名称由产品和年份组成,并用"分隔. (例如111.2000):

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)})

直到现在,我使用mapply运行乘法:

Until now I run 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中的名称匹配.有任何想法吗?

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?

注意:产品名称也可以包含2位数字,而不仅仅是3位.因此,我需要使用."前面的数字进行匹配.谢谢

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

推荐答案

您可以使用Map循环显示B和B名称,这也将保持名称不变:

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

这篇关于R:如何根据两个列表的名称在两个列表上运行函数/计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆