在函数内打印或显示变量

Mar*_*ler 10 printing r

有没有办法print在函数内部显示或显示变量的值,而不是在调用函数后在函数外部打印值?

我几乎可以肯定存在并认为代码被调用reveal或类似的东西,但我不记得正确的术语.

my.function <- function(x) {

  y <- x^2
 #  reveal(y)
 #  display(y)

 # desired result is to print or display here:
 # [1] 16

  cat(y)
  print(y)
  return(y)  
}

x <- 4

my.function(x)
#16[1] 16
#[1] 16
Run Code Online (Sandbox Code Playgroud)

cat(y),print(y)以及return(y)功能之外的所有打印.谢谢你的任何建议.

编辑

我在这里发现了类似的问题:

https://stat.ethz.ch/pipermail/r-help/2002-November/027348.html

Peter Dalgaard对该问题的回答是取消选中标签buffered output下的一个Misc选项.但是,这似乎并不适用于我的情况.也许这些问题是无关的.

42-*_*42- 13

您可以在函数内部放置print()调用,如果执行到达该点,则即使稍后发生错误,也会在控制台上生成输出.

 > myf <- function(x){ print(x); y <- x^2; print(y); error() }
> myf(4)
[1] 4
[1] 16
Error in myf(4) : could not find function "error"
Run Code Online (Sandbox Code Playgroud)

使用browser()函数作为调试路径可能更优雅.您可以通过更改选项()来设置其操作:

> options(error=recover)
> myf(4)
[1] 4
[1] 16
Error in myf(4) : could not find function "error"

Enter a frame number, or 0 to exit   

1: myf(4)

Selection: 1
Called from: top level 
Browse[1]> x
[1] 4
Browse[1]> y
[1] 16
Browse[1]>    # hit a <return> to exit the browser 

Enter a frame number, or 0 to exit   

1: myf(4)

Selection: 0   # returns you to the console
Run Code Online (Sandbox Code Playgroud)


Gar*_*man 12

我喜欢使用该message函数进行打印以进行调试,因为它似乎从它可能发出的任何黑暗深度到达控制台.例如:

somefunc <- function(x) {
       message(paste('ok made it this far with x=',x))
       # some stuff to debug
       message(paste('ok made it this far with x^2=',x^2))
       # some more stuff to debug
       message(paste('ok made it to the end of the function with x^3=',x^3))
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ler 7

当我问这个问题时,我可能一直在考虑show允许您查看变量值而不在return语句中包含该变量的函数。虽然,该show命令会打印函数之外的值。

my.function <- function(x) {
     y <- x^2
     show(y)
     show(length(y))
     z <- y + x
     return(z)
}

x <- 1:10

my.function(x)

 # [1]   1   4   9  16  25  36  49  64  81 100
 # [1] 10
 # [1]   2   6  12  20  30  42  56  72  90 110
Run Code Online (Sandbox Code Playgroud)

编辑:2021 年 3 月 19 日

从函数内部查看结果的另一种方法是将对象发送到全局变量。这可能有助于定位函数内的错误。

my.function <- function(x) {
     y <- x^2
     y <<- y
     z <- y + x
     z <<- z
     return(z)
}
y
#[1]   1   4   9  16  25  36  49  64  81 100
z
#[1]   2   6  12  20  30  42  56  72  90 110
x <- 1:10
my.function(x)
#[1]   2   6  12  20  30  42  56  72  90 110
Run Code Online (Sandbox Code Playgroud)