首页 > 解决方案 > 使用自定义打印方法打印列表时如何防止/删除控制台中的空白行

问题描述

我正在尝试为类 foo 的对象(基本上是一个列表)重现打印的 tibble 方式。

单独打印每个列表元素时,没有问题。但是当我尝试对每个列表元素使用编程方法时,它会在控制台中添加一个空白行,这是我不想要的。我该如何防止这种情况发生?

foo_obj <- list(a = "hello", b = "world")
class(foo_obj) <- c("fooclass")

myfooter <- function(x, width) {
  footer <- paste0(cli::symbol$ellipsis, " ", x)
  pillar::style_subtle(paste("#", footer))
}
print.fooclass <- function(x, ...) {
    print(x$a)
    cat(myfooter("s\n\n", 40))
    
    print(x$b)
    cat(myfooter("s", 40))
}

## This is the desired output
foo_obj
#> [1] "hello"
#> # … s
#> 
#> [1] "world"
#> # … s

print.fooclass_ls <- function(x, ...) {
lapply(1:length(x), function(i){
 print(x[i])
 cat(myfooter("s\n", 40))
}
)
}
class(foo_obj) <- c("fooclass_ls")

## The empty lines after the print are NOT desired
foo_obj
#> $a
#> [1] "hello"
#> 
#> # … s
#> $b
#> [1] "world"
#> 
#> # … s

reprex 包创建于 2021-03-10 (v1.0.0)

标签: r

解决方案


感谢 user20650 的好主意!- 我会按照他们的建议和自我回答。

列表对象使用换行符打印 - 但如果我们打印子元素[[i]],则没有换行符。为了打印名称,您还需要添加名称!

foo_obj <- list(a = "hello", b = "world")
class(foo_obj) <- c("fooclass")

myfooter <- function(x) {
  footer <- paste0(cli::symbol$ellipsis, " ", x)
  pillar::style_subtle(paste("#", footer))
}

print.fooclass <- function(x, ...) {
  lapply(1:length(x), function(i){
    cat(paste0("$", names(x)[i], "\n")) # for the names, which I want
    print(x[[i]])
    cat(myfooter("s\n\n"))
  }
  )
}

foo_obj
#> $a
#> [1] "hello"
#> # … s
#> 
#> $b
#> [1] "world"
#> # … s

reprex 包于 2021-03-11 创建(v1.0.0)


推荐阅读