在knitr输出期间从函数输出html

时间:2017-02-07 13:13:35

标签: html r rstudio knitr r-markdown

这是我想要一起运行的许多单独分析的一小部分,使用函数中生成的标题标记每个分析。第一个标题按预期输出,但函数生成的标题不会。如何将函数生成的标题格式化为html?

R version 3.3.2 (2016-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X El Capitan 10.11.6

RStudio 1.0.136

knitr 1.15.1
Dim WSh As Object
Set WSh = CreateObject("Wscript.Shell")
WSh.Run "C:\WINDOWS\system32\rundll32.exe %SystemRoot%\system32\van.dll,RunVAN", , True
Sleep 200
WSh.SendKeys " "
Sleep 1000
WSh.SendKeys "{ESC}"

1 个答案:

答案 0 :(得分:0)

我认为你必须使用results = 'asis'并改变你的功能以获得你想要的输出。我将使用previous question中引用的一些方法来使用包pander

您不必使用htmPrint功能,因为您可以使用cat和html标记获得相同的功能。然后,您只需使用print_lm代替print并删除摘要,因为您获得了很好的表格输出。

```{r initialize, echo=F, comment=NA}

library(pander)

#Use the pander print method to print the model tables.  
#You could use other package print methods as well.

print_lm <- function (x, ...) UseMethod("pander")

doAnalysis = function(dat, depVar, indVar) {

    cat('<h3>AusMCP1 on ', indVar, '</h3>')
    eval(parse(text=paste0('print_lm(summary(lm(', depVar, '~', indVar, ', data=dat)))')))
    cat('<hr>')
    }

demoData = data.frame(dep1=rnorm(100), dep2=rnorm(100), ind1=runif(100), ind2=runif(100), ind3=runif(100))

varDep = names(demoData)[1:2]
varInd = names(demoData)[3:5]
```

I  use *results=asis* and changed the output of your doAnalysis function to create formatted output.

```{r doAnalyses, echo = FALSE, results='asis'}
cat('<h2>Begin analyses</h2>')

for (k in 1:length(varDep)) for (i in 1:length(varInd)) doAnalysis(demoData, varDep[k], varInd[i])
```

enter image description here

您也可以事先进行所有建模,并使用broom包来根据自己的喜好整理所有模型摘要,然后使用您选择的kable()或表格打印方法将其打印出来