假设我有一个列表变量rho
,如下面的
$rs6139074
V4 V5 V7
4 0.9 0.0 0.1
5 0.0 0.9 0.0
7 0.1 0.0 0.9
$rs6139072
V4 V5 V7
4 0.9 0.0 0.1
5 0.0 0.8 0.0
7 0.1 0.0 0.9
如何提取每个列表的前2×2矩阵如下?
$rs6139074
V4 V5
4 0.9 0.0
5 0.0 0.9
$rs6139072
V4 V5
4 0.9 0.0
5 0.0 0.8
目的是做到这一点
lappy(rho[1:2,1:2],function(x) eigen(x)$values)
rho <- structure(list(rs6139074 = structure(c(0.9, 0, 0.1, 0, 0.9, 0,
0.1, 0, 0.9), .Dim = c(3L, 3L), .Dimnames = list(c("4", "5",
"7"), c("V4", "V5", "V7"))), rs6139072 = structure(c(0.9, 0,
0.1, 0, 0.8, 0, 0.1, 0, 0.9), .Dim = c(3L, 3L), .Dimnames = list(
c("4", "5", "7"), c("V4", "V5", "V7")))), .Names = c("rs6139074",
"rs6139072"))
答案 0 :(得分:2)
您可以使用lapply
循环变量和subset
:
lapply(rho, function(mat) mat[1:2, 1:2])
给出:
$rs6139074
V4 V5
4 0.9 0.0
5 0.0 0.9
$rs6139072
V4 V5
4 0.9 0.0
5 0.0 0.8
答案 1 :(得分:1)
我们可以将sapply
与simplify = FALSE
sapply(rho, function(mat) mat[1:2, 1:2], simplify = FALSE)
#$rs6139074
# V4 V5
#4 0.9 0.0
#5 0.0 0.9
#$rs6139072
# V4 V5
#4 0.9 0.0
#5 0.0 0.8