在R中打印不带行号的列表列表

时间:2018-09-29 11:24:19

标签: r list indexing

我想删除R中列表列表中的行号。 我已经检查过this solution,但是使用row.names = FALSE不适用于列表列表。例如:

C= list(listA = list(1:3, structure(1:9, .Dim = c(3L, 3L)), 4:9), 
    listB = list(c("t1", "t2", "t3"), structure(c("p1", "p2"), .Dim = 2:1)))

print(C)print(C, row.names = FALSE)的结果相同:

$`listA`
$`listA`[[1]]
[1] 1 2 3

$`listA`[[2]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

$`listA`[[3]]
[1] 4 5 6 7 8 9


$listB
$listB[[1]]
[1] "t1" "t2" "t3"

$listB[[2]]
     [,1]
[1,] "p1"
[2,] "p2"

我的预期输出是:

$listA
$listA[[1]]
1 2 3

$listA[[2]]

1    4    7
2    5    8
3    6    9

$listA[[3]]
4 5 6 7 8 9


$listB
$listB[[1]]
"t1" "t2" "t3"

$listB[[2]]

"p1"
"p2"

这是非常长的列表列表的另一个示例,我无法删除行号:

C1 = list(sector6_T06 = structure(list(I_1 = c(0.138020551652649, 
0.144926670928027, 0.149053631932294, 0.141536613829619, 0.141702678898179, 
0.137570073218103, 0.137138016297551, 0.1353084643726, 0.122970865726172, 
0.113268846326401, 0.0963028537881388, 0.0903790807114376, 0.0874631650322059, 
0.085312817477299, 0.0824981588006636, 0.0813193127885678, 0.0802771152566699, 
0.0793845870225118, 0.0790157481266558, 0.0786926819627487, 0.0781238524715645, 
0.0777219122602425, 0.0775867136030337, 0.0774915610454734), 
    I_2 = c(0.219262966881223, 0.229247895586232, 0.237229575776489, 
    0.220354084548452, 0.208789770302538, 0.202169506828404, 
    0.200538005582317, 0.198253713943851, 0.176174353994156, 
    0.16630312132205, 0.139566647564992, 0.132004716651325, 0.130368509974452, 
    0.123749451268899, 0.120567292287923, 0.119242120883444, 
    0.118075055976716, 0.117079181022326, 0.116668142679692, 
    0.116308335194556, 0.115677490002872, 0.115233134393343, 
    0.115083945213702, 0.114979230544904), I_3 = c(0.304931072097664, 
    0.317975507940971, 0.330725110764882, 0.301488240135078, 
    0.269040556975353, 0.259788621772735, 0.255920833087015, 
    0.252950729743552, 0.219115116915787, 0.210619055246998, 
    0.17355685687669, 0.16425036406777, 0.164199571882626, 0.152387183269087, 
    0.148995928793151, 0.147587257891481, 0.146348586161128, 
    0.145293132510833, 0.144857783790805, 0.144476795276745, 
    0.143809772751329, 0.143340496213876, 0.143183050013913, 
    0.143072663566612)), row.names = c(NA, -24L), class = "data.frame"))

1 个答案:

答案 0 :(得分:2)

这是一个非常肮脏的解决方案:

format.list <- function (l) {
    s <- capture.output(print(l))
    writeLines(
        sub("^ *(\\[,\\d+\\] *)+$", "",        # Remove indices from second dimension.
            sub("^ *\\[\\d+,?\\] *", "", s)))  # Remove indices from first dimension.
}
>> format.list(C)
$listA
$listA[[1]]
1 2 3

$listA[[2]]

1    4    7
2    5    8
3    6    9

$listA[[3]]
4 5 6 7 8 9


$listB
$listB[[1]]
"t1" "t2" "t3"

$listB[[2]]

"p1"
"p2"

如果要支持3个或更多维数组,也可以添加。