在函数内部打印或显示变量 [英] print or display variable inside function

查看:79
本文介绍了在函数内部打印或显示变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to print or display the value of a variable while inside a function, as opposed to printing the value outside the function after the function has been called?

我几乎确定存在并且认为代码被称为 reveal 或类似的东西,但我想不起来正确的术语.

I am virtually certain there is and thought the code was called reveal or something similar, but I cannot recall the correct term.

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

cat(y)print(y)return(y) 都在函数外打印.感谢您的任何建议.

cat(y), print(y) and return(y) all print outside the function. Thank you for any advice.

编辑

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

I found a similar question here:

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

Peter Dalgaard 对这个问题的回答是取消选中 Misc 选项卡下名为 buffered output 的选项.但是,这在我的情况下似乎不起作用.也许这些问题是无关的.

The response to that question from Peter Dalgaard was to uncheck an option called buffered output under the Misc tab. However, that does not seem to be working in my case. Perhaps the questions are unrelated.

推荐答案

您可以将 print() 调用(或 cat() 调用)放在函数,如果执行到该点,那么即使稍后在执行中发生错误,也会在控制台上产生输出.

You can put print() calls (or cat() calls for that matter) inside the function and if the execution reaches that point, then an output will be produced on the console even if an error later occurs later in execution.

 > 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"

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

It's probably more elegant to use the browser() function as the debugging route. You set up its operation by changing options():

> 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

这篇关于在函数内部打印或显示变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆