r - 使用自定义打印方法打印列表时如何防止/删除控制台中的空白行
问题描述
我正在尝试为类 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)
解决方案
感谢 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)
推荐阅读
- java - 为什么 ExecutorService 从类加载器线程启动时不处理提交的任务?
- c# - Winforms 应用程序 - 无法加载文件或程序集“实体框架”
- javascript - 在另一个函数中注入数据
- excel - 使用 excel vba 使用 FSO 方法将特定文件扩展名复制到另一个文件夹
- ios - 如何添加约束以使视图的尺寸在方向改变时不会改变?
- sql - SQL Anywhere 错误 - 对“分数”的函数或列引用也必须出现在 GROUP BY 中
- reactjs - 反应无法获取到数组
- html - vba:如何单击 iframe 中的元素
- python - 如何使用 numpy linalg 求解器进行多维使用?
- java - 为什么这段代码打印超类而不是子类的值