R 隐式调用什么函数来打印表达式的返回值?

问题描述 投票:0回答:1

当我在 R 提示符中输入表达式时,结果通常会打印到终端,除非有什么原因阻止:

> 1+1
[1] 2
> 1:10
 [1]  1  2  3  4  5  6  7  8  9 10
> invisible(1:10) # This prints nothing

我正在尝试设置 R 在打印任何内容之前立即评估一些代码。最明显的做法是使用

trace
将表达式添加到
print
的主体中。当显式调用
print
时,这会产生预期的效果,但在简单地计算表达式并让它自动打印时则不会:

> trace(print, tracer = expression({cat("printing\n")}), print = FALSE)
> print(1:10) # Explicit print: trace code is executed
printing
 [1]  1  2  3  4  5  6  7  8  9 10
> 1:10 # Implicit print: no trace
 [1]  1  2  3  4  5  6  7  8  9 10

很明显,当 R 只是想打印表达式的结果时,它实际上并没有调用

print
,即使结果与显式调用
print
相同。那么它调用的是哪个函数(如果有的话)?有没有什么函数可以代替 print 来让 R 在隐式打印之前评估我的代码?

如果有人想知道,我真正想要执行的代码是这个函数,它告诉 R 当前终端窗口宽度,以便它在打印内容时可以使用完整宽度:

get_terminal_width <- function() { cols <- as.numeric(Sys.getenv("COLUMNS")) if (!is.na(cols)) { return(cols) } cols <- as.numeric(system2("tput", "cols", stdout = TRUE)) if (!is.na(cols)) { return(cols) } return(NA_integer_) } update_width <- function(...) { try(options(width=as.character(get_terminal_width()-1)), silent = TRUE) }


r output
1个回答
0
投票
https://cran.r-project.org/doc/manuals/r-release/R-ints.html

© www.soinside.com 2019 - 2024. All rights reserved.