Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 打印矢量时更改索引_R_Pretty Print_Tail - Fatal编程技术网

R 打印矢量时更改索引

R 打印矢量时更改索引,r,pretty-print,tail,R,Pretty Print,Tail,我想为R做一个函数,然后显示这两个。这个问题的解决方案基本上是建议这样一个版本(稍加修改),效果很好 ht <- function(x, n = 6L, m=n, returnList=FALSE, ...) { if (!returnList) { print(head(x, n, ...)) cat("...\n") print(tail(x, m, ...)) invisible(NULL) }

我想为R做一个函数,然后显示这两个。这个问题的解决方案基本上是建议这样一个版本(稍加修改),效果很好

ht <- function(x, n = 6L, m=n, returnList=FALSE, ...) {

    if (!returnList) {
        print(head(x, n, ...))
        cat("...\n")
        print(tail(x, m, ...))
        invisible(NULL)
    }   
    else {
        list(head = head(x, n, ...), tail = tail(x,m, ...))
    }
}
和矩阵

> ht(diag(10), 3)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    0    0    0    0    0    0    0    0     0
[2,]    0    1    0    0    0    0    0    0    0     0
[3,]    0    0    1    0    0    0    0    0    0     0
...
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[8,]     0    0    0    0    0    0    0    1    0     0
[9,]     0    0    0    0    0    0    0    0    1     0
[10,]    0    0    0    0    0    0    0    0    0     1
和向量

> ht(1:10, 3)
[1] 1 2 3
...
[1]  8  9 10
但是,我不喜欢输出查找向量的方式。上面的示例中显示了两个问题:

  • 数字之间的间距不同,因为尾端包含两位数字的“10”,而前端仅包含一位数字

  • 尾端的索引从[1]开始,但我希望它从[8]开始

  • 所以我希望输出(向量)像这样

    > ht(1:10, 3)
    [1]  1  2  3
    ...
    [8]  8  9 10
    
    第一个问题可能可以通过对提取的向量进行一点簿记来解决。可能很乏味但可行。但是,如果不完全自己重新创建输出,我看不出如何解决第二个问题
    tail()
    返回一个向量,因此
    tail(1:10,3)
    s索引从1开始并不奇怪,因为向量
    c(8,9,10)
    被传递到
    print.default()

    现在,尾部输出可以像下面这样开始,但是如果行太长,会弄乱间距并导致各种问题,因为它没有像
    print.default()
    确保的那样以漂亮的方式包装

    ht2 <- function(x, n = 6L, m=n, returnList=FALSE, ...) {    
        start <- length(x)-n+1
        cat("[", start,"] ", paste0(tail(x, m), sep=" "), sep="")
    }
    

    ht2对于间距问题,向量似乎没有什么特别之处。。。如果
    ht(1:10,3)
    让你讨厌,为什么不
    ht(矩阵(1:(5*1000),ncol=5,byrow=T),3)
    ?@Gregor是的,这也让我讨厌。但我想如果我能处理向量的情况,我可以在各种特殊情况下解决这个问题
    ht2 <- function(x, n = 6L, m=n, returnList=FALSE, ...) {    
        start <- length(x)-n+1
        cat("[", start,"] ", paste0(tail(x, m), sep=" "), sep="")
    }