R:如何在函数中打印计算列表元素的名称?

时间:2015-12-14 20:17:37

标签: r function

我有两个超过1500个元素的列表,一个矢量列表和一个矩阵列表。这里有一些示例数据:

Z_matr <- list("111.2012"= matrix(c(0,0,100,200,0,0,0,0,50,350,0,50,50,200,200,0),
                             nrow = 4, ncol = 4, byrow = T),
           "112.2012"= matrix(c(10,90,0,30,10,90,0,10,200,50,10,350,150,100,200,10),
                              nrow = 4, ncol = 4, byrow = T))
p <- list("111.2012"=c(200, 1000, 100, 10), "112.2012"=c(300, 900, 50, 100))

在这两个列表中,我想执行以下功能,当然可以正常使用这个数据:

kast <- function(Z_matr, p) {
  imp <- rowSums(Z_matr)
  exp <- colSums(Z_matr)
  x = p + imp
  ac = p + imp - exp  
  einsdurchx = 1/as.vector(x)    
  einsdurchx[is.infinite(einsdurchx)] <- 0
  A = Z_matr %*% diag(einsdurchx)
  return(A)
}

mapply(kast, Z_matr,p, SIMPLIFY=FALSE)

然而,我在原始列表中遇到错误。我需要的是计算在错误列表元素之前已经计算过的列表名称(这样我知道哪个列表组合会产生错误)。所以,我尝试print(names(A))然而我只得到NULL,NULL ...我怎么能得到这个,对于这个例子111.2012和112.2012 with print?

1 个答案:

答案 0 :(得分:1)

设置它以便传递名称并用于索引对象:

kast <- function(item, p) { print(item)
  imp <- rowSums(Z_matr[[item]])
  exp <- colSums(Z_matr[[item]])
  x = p + imp
  ac = p + imp - exp  
  einsdurchx = 1/as.vector(x)    
  einsdurchx[is.infinite(einsdurchx)] <- 0
  A = Z_matr[[item]] %*% diag(einsdurchx)
  return(A)
}

mapply(kast, names(Z_matr),p, SIMPLIFY=FALSE)

输出......显然你取出了print语句:

[1] "111.2012"
[1] "112.2012"
$`111.2012`
     [,1] [,2]      [,3]      [,4]
[1,]  0.0 0.00 0.1818182 0.4347826
[2,]  0.0 0.00 0.0000000 0.0000000
[3,]  0.1 0.35 0.0000000 0.1086957
[4,]  0.1 0.20 0.3636364 0.0000000

$`112.2012`
           [,1]       [,2]       [,3]       [,4]
[1,] 0.02325581 0.08910891 0.00000000 0.05357143
[2,] 0.02325581 0.08910891 0.00000000 0.01785714
[3,] 0.46511628 0.04950495 0.01515152 0.62500000
[4,] 0.34883721 0.09900990 0.30303030 0.01785714

使用s/lapplymapply这是一个长期存在的问题。只有值而不是列表项的名称才会传递给函数。它们仅在处理后添加回来。如果您尝试将print(deparse(substitute(Z_matr)))作为示例函数中的第一个调用,则可以看到此内容。