R中的跟踪功能 [英] Tracing functions in R

查看:106
本文介绍了R中的跟踪功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想跟踪一个函数,以便它在调用
时打印所有参数,并在返回结果时将返回值与参数一起打印。
函数跟踪允许定义在进入和退出函数调用时要执行的操作。
是否有一个函数返回该函数中的参数列表,并且有没有一种方法可以获取结果值而无需执行每个分支退出函数的多个分支
中的每个分支?

I want to trace a function so that it prints all of its arguments at the call and it prints the return value together with the arguments when it returns the result. The function trace allows to define action to be performed on entering and on exiting a function call. Is there a function returning the list of arguments within the function, and is there a way of getting the result value without doing each one of multiple branches where each branch exits the function?

跟踪应在调用时打印两个输入参数
(或函数调用本身为文本)的列表,并在所有函数退出时返回返回值

in the following example, tracing should print a list of both input parameters (or the function call as text itself) at the call and the return value when the function exits in any one of the branches.

myfun <- function(a,b){
  if (a==1) return(b+1)
  if (a==2) return(b*10)
  return(b)
}


推荐答案

您正在寻找 match.call()和 returnValue()

myfun <- function(a,b){
    if (a==1) return(b+1)
    if (a==2) return(b*10)
    return(b)
}

trace("myfun", tracer = substitute(print(as.list(match.call()))),
      exit = substitute(print(returnValue())))
#> [1] "myfun"

myfun(1, 2)
#> Tracing myfun(1, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(1, 2) on exit 
#> [1] 3
#> [1] 3
myfun(2, 2)
#> Tracing myfun(2, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 2
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(2, 2) on exit 
#> [1] 20
#> [1] 20
myfun(3, 2)
#> Tracing myfun(3, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 3
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(3, 2) on exit 
#> [1] 2
#> [1] 2

reprex软件包(v0.2.1)

Created on 2018-10-07 by the reprex package (v0.2.1)

Moody_Mudskipper 提到,在注释中,您还可以使用 quote()而不是 substitute()

As Moody_Mudskipper mentions, in the comments, you can also use quote() rather than substitute():

myfun <- function(a,b){
    if (a==1) return(b+1)
    if (a==2) return(b*10)
    return(b)
}

trace("myfun", tracer = quote(print(as.list(match.call()))),
      exit = quote(print(returnValue())))
#> [1] "myfun"

myfun(1, 2)
#> Tracing myfun(1, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(1, 2) on exit 
#> [1] 3
#> [1] 3
myfun(2, 2)
#> Tracing myfun(2, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 2
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(2, 2) on exit 
#> [1] 20
#> [1] 20
myfun(3, 2)
#> Tracing myfun(3, 2) on entry 
#> [[1]]
#> myfun
#> 
#> $a
#> [1] 3
#> 
#> $b
#> [1] 2
#> 
#> Tracing myfun(3, 2) on exit 
#> [1] 2
#> [1] 2

reprex包(v0.2.1)

Created on 2018-10-07 by the reprex package (v0.2.1)

有关两者之间的区别,请参见此堆栈溢出问题

For an illustration of the difference between the two, see this Stack Overflow question.

这篇关于R中的跟踪功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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