Sexpr中的错误处理

时间:2016-04-13 08:06:42

标签: r error-handling try-catch knitr

如何在\Sexpr

中允许错误?

我有一份针织文件。本文档的一小部分是指无法共享的文件。因此,每当根据正在读取的文件的某个对象\Sexpr{a}调用a时,它就会返回错误。我希望代替\Sexpr打印它遇到错误。

例如,

\documentclass{article}
\usepackage{xcolor}  % for red

\begin{document}

<<>>=
x <- 1
@

The value of $x$ is \Sexpr{x}

<<>>=
a <- scan("secret_file.txt")
@
The value of $a$ is \Sexpr{a}.

\end{document}

将无法编译(当secret_file.txt不存在时)。我希望输出看起来像:Sexpr-error-detected

我认为改变inline钩子会起作用,但是把下面的块子没有区别。

<<Sexpr-setup>>=
library(knitr)
knit_hooks$set(inline = function(x){
  out <- tryCatch(
    {
      if (is.numeric(x)) 
        x = round(x, getOption("digits"))
      paste(as.character(x), collapse = ", ")
    }, 
    error = function(cond){
      return("\\textcolor{red}{\\textbf{Sexpr error!}}")
      invisible(NULL)
    }, 
    warning = function(cond){
      return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
      invisible(NULL)
    }
  )
  return(out)
})
@

拥有自定义错误消息并不是必需的,只是输出中的错误是明确的,并且不会阻止编译。我感谢我可以将{替换为\Sexpr{XX(之类的内容替换为XX()并执行相同的tryCatch maneouvre,但我认为knitr could do this

在上面调用knitr::knit并应用回溯显示:

11: eval(expr, envir, enclos)
10: eval(parse_only(code[i]), envir = envir)
9: withVisible(eval(parse_only(code[i]), envir = envir))
8: inline_exec(block)
7: in_dir(opts_knit$get("root.dir") %n% input_dir(), inline_exec(block))
6: call_inline(x)
5: process_group.inline(group)
4: process_group(group)
3: withCallingHandlers(if (tangle) process_tangle(group) else process_group(group), 
       error = function(e) {
           setwd(wd)
           cat(res, sep = "\n", file = output %n% "")
           message("Quitting from lines ", paste(current_lines(i), 
               collapse = "-"), " (", knit_concord$get("infile"), 
               ") ")
       })
2: process_file(text, output)
1: knitr::knit("knitr-prevent-errors.Rnw", quiet = TRUE)

从以下功能开始,

处的错误似乎很低
eval(parse_only(code[i]), envir = envir)

code[i]a的位置。我是否正确地认为解决此问题的唯一方法是使用v =更改以tryCatch开头的行?

1 个答案:

答案 0 :(得分:5)

使用设置块中的选项include=FALSE,以下输出对我有效。如果它不适合你,我会删除帖子

enter image description here

\documentclass{article}
\usepackage{xcolor}  % for red


<<setup, include=FALSE>>= 
knit_hooks$set(inline = function(x) {

out <- tryCatch(
    {
      if (is.numeric(x)) 
        x = round(x, getOption("digits"))
      paste(as.character(x), collapse = ", ")
    }, 
    error = function(cond){
      return("\\textcolor{red}{\\textbf{Sexpr error!}}")
      invisible(NULL)
    }, 
    warning = function(cond){
      return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
      invisible(NULL)
    }
  )

return(out)

})
@ 



\begin{document}

<<>>=
x <- 1
@

The value of $x$ is \Sexpr{x}

<<>>=
a <- scan("secret_file.txt")
@
The value of $a$ is \Sexpr{a}.

\end{document}

Knitr输出:

>knitr::knit("test.Rnw")


processing file: test.Rnw
  |.........                                                        |  14%
  ordinary text without R code

  |...................                                              |  29%
label: setup (with options) 
List of 2
 $ include: logi FALSE
 $ indent : chr "    "

  |............................                                     |  43%
  ordinary text without R code

  |.....................................                            |  57%
label: unnamed-chunk-1 (with options) 
List of 1
 $ indent: chr "    "

  |..............................................                   |  71%
   inline R code fragments

  |........................................................         |  86%
label: unnamed-chunk-2 (with options) 
List of 1
 $ indent: chr "    "

  |.................................................................| 100%
   inline R code fragments


output file: test.tex

[1] "test.tex"

Tex输出:

>texi2pdf("test.tex")
>

我在Windows上使用MikTex 2.9,knitr 1.9,R 3.0.2,请你附上你的日志文件然后我们可以比较差异,如果有的话