从保存在R中多个列表的矩阵对角线中提取元素

时间:2018-07-19 13:58:01

标签: r list elements diagonal

我正在尝试从保存为列表的多个对角线中获取不同的元素。我的数据看起来像这样:

res <- list()
res[[1]] <- matrix(c(0.04770856,0.02854005,0.02854005,0.03260190), nrow=2, ncol=2)
res[[2]] <- matrix(c(0.05436957,0.04887182,0.04887182, 0.10484454), nrow=2, ncol=2)

> res
[[1]]
           [,1]       [,2]
[1,] 0.04770856 0.02854005
[2,] 0.02854005 0.03260190

[[2]]
           [,1]       [,2]
[1,] 0.05436957 0.04887182
[2,] 0.04887182 0.10484454

> diag(res[[1]])
[1] 0.04770856 0.03260190
> diag(res[[2]])
[1] 0.05436957 0.10484454

我想将给定列表的每个对角线的第一和第二个元素保存到类似于此的向量中:

d.1st.el <- c(0.04770856, 0.05436957)
d.2nd.el <- c(0.03260190, 0.10484454)

我的问题是编写为所有给定列表运行的函数并获取对角线。出于某种原因,当我使用unlist()提取给定级别的每个矩阵的值时,它不会得到数字,而是完整的矩阵。

有人有一个简单的解决方案吗?

2 个答案:

答案 0 :(得分:2)

sapply(res, diag)

           [,1]       [,2]
[1,] 0.04770856 0.05436957
[2,] 0.03260190 0.10484454

# or
lapply(res, diag)
[[1]]
[1] 0.04770856 0.03260190

[[2]]
[1] 0.05436957 0.10484454

如果出于某种原因想要在全局环境中使用向量,则

alld <- lapply(res, diag)
names(alld) <- sprintf("d.%d.el", 1:length(alld))
list2env(alld, globalenv())

答案 1 :(得分:0)

您可以分两个步骤进行操作:

# Step 1 - Get the diagonals
all_diags <- sapply(res, function(x) diag(t(x)))

print(all_diags)

           [,1]       [,2]
[1,] 0.04770856 0.05436957
[2,] 0.03260190 0.10484454

# Step 2 - Append to vectors

d.1st.el <- all_diags[1,]
d.2nd.el <- all_diags[2,]