Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: conditionally evaluate normal chunks

Tags:

r

knitr

Here's what I'd like to do, in my Rhtml document:

<!--begin.rcode
if (errors==1) {
end.rcode-->
<p>You have an error!</p>
<!--begin.rcode

end.rcode-->

Basically, I'm trying to use knitr like PHP. The above doesn't work, but is there a right way to do it?

This question is different from Conditional `echo` (or eval or include) in rmarkdown chunks. That is about how to conditionally evaluate a knitr "chunk". This is about how to conditionally evaluate the "normal" HTML (or TeX, or Markdown) in between two knitr chunks.


1 Answers

You can use a normal if block in the chunk. If you want an HTML formatted error message, you can use results='asis' in the chunk options. Like this:

<!--begin.rcode results='asis'
if (errors==1) {
  cat('<p>You have an error</p>')
} else {
  # r code to evaluate when errors!=1
}
end.rcode-->
like image 123
arvi1000 Avatar answered Feb 06 '26 14:02

arvi1000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!