假设我有一个小的矩阵列表,并希望提取每个矩阵的加入。
除了循环attr()
函数之外,还有什么好办法吗?
矩阵数据:
tfmatrx<-list(
MA0275.1 = structure(c(0, 76, 0, 24, 0, 100, 0, 0, 0, 0,
100, 0, 0, 0, 100, 0, 72, 11, 16, 0, 53, 0, 0, 47), .Dim = c(4L,
6L), .Dimnames = list(c("A", "C", "G", "T"), NULL), id = "MA0275.1", accession = "ASG1"),
MA0276.1 = structure(c(0, 220, 8, 35, 0, 291, 0, 3, 61, 21,
133, 10, 58, 54, 101, 12, 130, 0, 54, 0, 0, 11, 8, 147, 33,
150, 8, 35, 80, 0, 92, 26, 0, 8, 249, 19, 0, 0, 256, 18), .Dim = c(4L,
10L), .Dimnames = list(c("A", "C", "G", "T"), NULL), id = "MA0276.1", accession = "ASH1"),
MA0277.1 = structure(c(63, 13, 13, 13, 100, 0, 0, 0, 100,
0, 0, 0, 88, 13, 0, 0, 75, 0, 25, 0, 0, 0, 100, 0, 78, 16,
3, 3, 81, 6, 6, 6, 63, 13, 13, 13), .Dim = c(4L, 9L), .Dimnames = list(
c("A", "C", "G", "T"), NULL), id = "MA0277.1", accession = "AZF1"),
MA0278.1 = structure(c(64, 217, 425, 292, 104, 552, 150,
192, 484, 111, 114, 288, 78, 401, 186, 333, 455, 51, 370,
122, 248, 34, 670, 46, 98, 724, 143, 33, 52, 918, 7, 20,
348, 346, 280, 24, 12, 3, 977, 6, 966, 5, 23, 4, 26, 6, 962,
4, 9, 10, 4, 975, 47, 930, 7, 15, 892, 42, 16, 49, 487, 123,
320, 68, 288, 140, 317, 254, 373, 110, 81, 434, 178, 367,
184, 268, 402, 140, 341, 114, 435, 229, 241, 94), .Dim = c(4L,
21L), .Dimnames = list(c("A", "C", "G", "T"), NULL), id = "MA0278.1", accession = "BAS1"))
我希望获得字符向量或data.frame中的所有加入。我知道如何为列表中的第一个元素做这个,但是如何为所有的加入做呢?
我想在这里实现的输出是:
ASG1 ASH1 ASF1 BAS1
names(tfmatrix)
提供所有名称但不包括加入,任何帮助都表示赞赏。
答案 0 :(得分:10)
怎么样
lapply(tfmatrx, attr, "accession")
$MA0275.1
[1] "ASG1"
$MA0276.1
[1] "ASH1"
$MA0277.1
[1] "AZF1"
$MA0278.1
[1] "BAS1"
你也可以使用sapply
,它可以很方便,因为输出是一个向量(尽可能地尝试简化结果)。
sapply(tfmatrx, attr, "accession")
MA0275.1 MA0276.1 MA0277.1 MA0278.1
"ASG1" "ASH1" "AZF1" "BAS1"
这相当于上面未列出的lapply
解决方案。
unlist(lapply(tfmatrx, attr, "accession"))
MA0275.1 MA0276.1 MA0277.1 MA0278.1
"ASG1" "ASH1" "AZF1" "BAS1"