2

如果我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

为什么会出现这种情况?

4

1 回答 1

0

This is an old question and this maybe wasn't possible then, but today you can intercept one of knitr's hooks:

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
})
于 2017-12-16T21:21:48.527 回答