【问题标题】:R trace doesn't work correctly inside functions?R 跟踪在函数内部无法正常工作?
【发布时间】:2016-01-06 10:00:35
【问题描述】:

trace 在预编译函数中似乎无法正常工作

比如在这个sn-p中

xx <- 2:7
nu <- seq(-10, 9, length.out = 2001)
op <- par(lab = c(16, 5, 7))
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))

xy.coords 的简单 trace 工作正常

trace(xy.coords)
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords

但是用函数追踪似乎不起作用

trace(xy.coords, tracer = quote(cat("test\n")))
# Tracing function "xy.coords" in package "grDevices"
# [1] "xy.coords"
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))

虽然直接调用工作正常

xy.coords(1:3, 1:2, recycle = TRUE)
# Tracing xy.coords(1:3, 1:2, recycle = TRUE) on entry 
# test
# $x
# [1] 1 2 3
# 
# $y
# [1] 1 2 1
# 
# $xlab
# NULL
# 
# $ylab
# NULL

发生了什么,我需要改变什么?

更新我禁用了grDevices 和其他base 软件包的编译,但trace 仍然无法正常工作。在调试matplot 时,xy.coords 似乎没有跟踪。

更新 2 这似乎与 Override a function that is imported in a namespace 有关,但在尝试了那里建议的一切并在命名空间中分配跟踪对象后,旧的仍然被调用。

【问题讨论】:

  • 如果需要,可以添加 where = matplotprint = FALSE

标签: r trace


【解决方案1】:

作用于图形的导入(matplot 所属的地方)似乎可以解决问题:

xx <- 2:7
nu <- seq(-10, 9, length.out = 2001)
op <- par(lab = c(16, 5, 7))

trace(xy.coords, tracer = quote(cat("test\n")))

# get the imports env of graphics
nsi <- parent.env(getNamespace('graphics'))

unlockBinding("xy.coords", nsi)
assign('xy.coords', xy.coords, nsi)

matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))


Tracing xy.coords(x, y, xlabel, ylabel, log = log) on entry 
test
Tracing xy.coords(x, y, xlabel, ylabel, log) on entry 
test
Tracing xy.coords(x, y) on entry 
test
Tracing xy.coords(x, y) on entry 
test
Tracing xy.coords(x, y) on entry 
test
Tracing xy.coords(x, y) on entry 
test
Tracing xy.coords(x, y) on entry 
test

【讨论】:

  • 谢谢,我没有意识到要查看导入命名空间
  • @RomanTsegelskyi 请解释为什么仅仅做trace(xy.coords, tracer = quote(cat("test\n")), where = matplot) 是不够的
  • 查看 trace() 代码,似乎没有跟踪器 arg,跟踪由 .Primitive(".primTrace") 执行,否则由 methods:::.TraceWithMethods() 执行。因此有两种不同的实现。
猜你喜欢
  • 1970-01-01
  • 2014-01-17
  • 2021-01-25
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多