Knitr HTML Loop - Some HTML output, some R output

落花浮王杯 提交于 2020-01-15 07:58:48

问题


i want to loop through a list and and print some part of it in HTML and some as Code. So be more precise: I want to produce the same output this is creating

<h2> 1 is a great number </h2> 
<!--begin.rcode echo=FALSE print(rnorm(5,mean=1)) end.rcode--> 
<h2> 2 is a great number </h2> 
<!--begin.rcode echo=FALSE print(rnorm(5,mean=2)) end.rcode-->
...
<h2> x is a great number </h2> 

I managed to print the 's to HTML but the results are printed directly in HTML as well, with the following Chunk:

<!--begin.rcode, echo=FALSE, results = 'asis'
for (i in list(1,2)){
   cat("<h2>", i, "is a great number</h2>")
   print(rnorm(5,mean=i))
}
end.rcode-->

Would be very happy about all suggestions.

P.S.: The reason why i want to have the formatting is that knirtBootstrap then produces a very nice Output.


回答1:


Hello again Floo0 an other solution using two .Rhtml files. The first one, mainfile.Rhtml, calls the second one as many time you want. In stepfile.Rhtml you can put chunks as you want. You just have to compile mainfile.Rhtml.

## mainfile.Rhtml

<!--begin.rcode echo=FALSE
J <- 10
end.rcode-->


<!--begin.rcode include=FALSE
out <- NULL
for (i in 1:J) {
  out <- c(out, knit_child('stepfile.Rhtml'))
}
end.rcode-->


<!--rinline paste(out, collapse = '\n') -->


## stepfile.Rhtml

<!--begin.rcode echo=FALSE, results='asis'
cat("<h2>", i, "is a great number</h2>")
end.rcode-->

<!--begin.rcode echo=FALSE
print(rnorm(5,mean=i))
end.rcode-->

I took the idea from Dynamic number of calls to a chunk with knitr




回答2:


With something like this :

<!--begin.rcode, echo=FALSE, results = 'asis'
for (i in list(1,2)){
   cat("<h2>", i, "is a great number</h2>")
   cat("</pre></div>")
   cat("<div class='output'><pre class='knitr r'>")
   cat("## ")
   print(rnorm(5,mean=i))
   cat("</pre></div>")
}
end.rcode-->

Does it help?




回答3:


I think this is a bad hack but you can do:

<!-- begin.rcode setup, include=FALSE
tmpl <- '<!-- begin.rcode tmpl-label-%d,
print(rnorm(5,mean=i))
\nend.rcode-->'
end.rcode-->

<!--begin.rcode echo=FALSE, results='asis'
for (i in 1:2) {
  cat("<h2>", i, "is a great number</h2>")
  cat(knit(text=sprintf(tmpl, i), quiet=TRUE))
}
end.rcode-->


来源:https://stackoverflow.com/questions/21856088/knitr-html-loop-some-html-output-some-r-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!