有一种新的可能性可以截取 html 小部件的屏幕截图以供进一步实施,例如 pdf 文档(您需要下载该软件包:webshot)。获取数据表(DT 包)的屏幕截图并用作rmarkdown 中的图像。您应该尝试一下,表格的格式很好。
这是一个示例代码:
---
output:
pdf_document:
toc: yes
---
```{r, fig.align='center', fig.pos='htb!', echo=FALSE, cache=FALSE, warning = FALSE, message = FALSE, tidy=TRUE}
library(DT)
library(webshot)
datatable(mtcars[1:15,],rownames=FALSE, options = list(dom='t',ordering=F))
```
更新
我已经尝试了你在this shiny app example基础上给我的完整代码
闪亮的应用程序:
library(shiny)
library(rmarkdown)
library(knitr)
shinyApp(
ui = fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
plotOutput('regPlot')
)
)
),
server = function(input, output) {
data <- reactive({mtcars[ ,input$x, drop=FALSE]})
regFormula <- reactive({
as.formula(paste('mpg ~', input$x))
})
output$regPlot <- renderPlot({
par(mar = c(4, 4, .1, .1))
plot(regFormula(), data = mtcars, pch = 19)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report_file.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report_file.Rmd', overwrite = TRUE)
library(rmarkdown)
out <- render('report_file.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
)
report_file.Rmd:
Here is my regression model:
```{r model, collapse=TRUE}
options(digits = 4)
fit <- lm(regFormula(), data = mtcars)
b <- coef(fit)
summary(fit)
```
```{r, fig.align='center', fig.pos='htb!', echo=FALSE, cache=FALSE, warning = FALSE, message = FALSE, tidy=TRUE}
library(DT)
library(webshot)
datatable(data(),rownames=FALSE, options = list(dom='t',ordering=F))
```
The fitting result is $mpg = `r b[1]` + `r b[2]``r input$x`$.
Below is a scatter plot with the regression line.
```{r plot, fig.height=5}
par(mar = c(4, 4, 1, 1))
plot(regFormula(), data = mtcars, pch = 19, col = 'gray')
abline(fit, col = 'red', lwd = 2)
```
它完美地为我提供了所需的 pdf 输出: