Conditionally display a block of text in R Markdown

后端 未结 7 1952
一向
一向 2020-12-01 05:12

I am using knitr to parse an R Markdown document . Is there a way to conditionally display a block of text in R Markdown depending on a variable in the environment I pass i

7条回答
  •  独厮守ぢ
    2020-12-01 05:49

    I tried to define a function my.render(), which preprocesses the Rmd file, and depending on the commentout argument, either keeps the HTML commenting code (TRUE) in the Rmd file or removes them (FALSE). Then writes the preprocessed Rmd file into tmp.Rmd, and uses the usual render() function.

    my.render <- function(input, commentout=FALSE, ...) {
      if (commentout == FALSE) {
        ## Delete the HTML comment lines from code
        txt <- readLines(input)
        txt[grepl(" * *", txt)] <- ""
        write.table(txt, file="tmp.Rmd", sep="\n", quote=FALSE, row.names=FALSE, col.names=FALSE)
        render("tmp.Rmd", output_file=sub("Rmd","html",input), ...)
      } else {
        render(input, output_file=sub("Rmd","html",input), ...)
      }
    }
    

    It seemed to work. E.g.

    
    

提交回复
热议问题