【问题标题】:Knitr HTML Loop - Some HTML output, some R outputKnitr HTML Loop - 一些 HTML 输出,一些 R 输出
【发布时间】:2014-03-18 08:14:17
【问题描述】:

我想遍历一个列表并将其中的一部分打印为 HTML 和一些代码。 所以更准确地说:我想产生与此相同的输出

<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> 

我设法将 's 打印到 HTML,但结果也直接打印在 HTML 中, 使用以下块:

<!--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-->

很高兴收到所有建议。

P.S.:我想要格式化的原因是knirtBootstrap,然后产生一个非常好的输出。

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    这样的:

    <!--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-->
    

    有帮助吗?

    【讨论】:

    • 您好维克多,感谢您的回答。我也想过这样的解决方案,但这种方式让 knitr 变得无稽之谈。这样你就可以开始自己编写所有的 HTML 环境了……这正是 knitr 应该为你做的工作。
    • 我明白...也许有一种方法可以处理子文档,请参阅 stackoverflow.com/questions/11956520/…Hugo Koopmans 的回答
    【解决方案2】:

    我认为这是一个糟糕的 hack,但你可以这样做:

    <!-- 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-->
    

    【讨论】:

      【解决方案3】:

      你好 Floo0 另一个使用两个 .Rhtml 文件的解决方案。第一个 mainfile.Rhtml 会根据需要多次调用第二个。在stepfile.Rhtml 中,您可以随意放置块。你只需要编译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-->
      

      我的想法来自Dynamic number of calls to a chunk with knitr

      【讨论】:

      • 您可以看看 knit_expand 作为 knit_child 的替代品。
      • 您可以将 stepfile.Rhtml 的开头简化为 &lt;h2&gt;&lt;!--rinline i--&gt; is a great number&lt;/h2&gt;(使用内联评估)。
      • 使用I(paste(out, collapse = '\n')) 使它工作。这删除了包装器,现在knirtBootstrap 可以很好地显示它。非常感谢!
      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多