【问题标题】:Knitr not producing what i am expecting if I cut and paste the code in R terminal如果我在 R 终端中剪切并粘贴代码,Knitr 不会产生我期望的结果
【发布时间】:2013-07-29 20:38:50
【问题描述】:

如果我knit下面这段代码:

```{r, eval=TRUE}
times <- function(total = 3, name="a") {
    ctr <- 1
    function(expr, val, ok, visible) {
        cat("[Task ", name, "] ", ctr,"\n", sep="")
        ctr <<- ctr + 1
        return(ctr <= total)
    }
}

h <- taskCallbackManager()
h$suspend()
h$add(times())
h$add(times(4,"b"))
h$add(times(5,"c"))
h$add(times(6,"d"))
h$suspend(FALSE)
```

在最后一个命令(h$suspend(FALSE)) 之后我没有任何输出。但是,如果我将代码剪切并粘贴到 R 中,我会得到以下输出:

[Task a] 1
[Task b] 1
[Task c] 1
[Task d] 1

为什么会出现这种情况?

【问题讨论】:

  • 这看起来很复杂。我的猜测是,回调是在 代码被评估之后执行的,并且评估(取决于 knitr)将无法捕获输出;非常欢迎对此问题感兴趣的任何人向github.com/hadley/evaluate提交补丁,谢谢! (相关部分在 eval.r 和 watcher.r)
  • 后续讨论是here,现在我认为解决这个问题是不可能的,但我会很高兴被证明是错误的。

标签: r knitr r-markdown


【解决方案1】:

这是一个老问题,当时这可能是不可能的,但今天你可以拦截knitr 的钩子之一:

knit_hooks$set(evaluate = function(...) {
  res  <- evaluate::evaluate(...)

  # instead of recordPlot()
  plot <- Filter(evaluate::is.recordedplot, res)
  plot <- if (length(plot)) plot[[1]]

  # expression and equivalent of the globalenv()
  args  <- list(...)
  env   <- args$envir
  expr  <- parse(text = paste(args[[1]], collapse = '\n'))

  # here call your actual callback

  # return the value that knitr expects
  res
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多