2016-06-13 171 views
2

我正在嘗試構建一個Shiny應用程序,並將其託管在我公司的Shiny服務器上,該服務器需要輸入的股票代碼並使用它從數據庫中提取數據並生成一系列圖並以markdown(.md)或word(.doc)格式表格。理想情況下,我會爲此應用程序提供三個文件:服務器,用戶界面和r降價模板。通過Shiny服務器將閃亮輸入傳遞給R markdown

我目前有一個使用SWeave的工作應用程序,但TeX文件在渲染中文字符時出現問題,所以我想使用RMD。

server.r:

library(knitr) 
shinyServer(function(input, output) { 
output$report = downloadHandler(
     filename = 'myreport.pdf', 
     content = function(file) { 
      out = knit2pdf('input.Rnw', clean = TRUE) 
      file.rename(out, file) # move pdf to file for downloading 
     }, 
     contentType = 'application/pdf' 
) 
}) 

ui.r:

library(shiny) 
shinyUI(basicPage(
textInput('stockcode', 'Stock Code:', value = '600340.SH'), 
downloadButton('report') 
)) 

input.Rnw:

\documentclass{article} 

\begin{document} 
\SweaveOpts{concordance=TRUE} 

<<initialize, echo = FALSE, results = 'hide'>>= 
library(ggplot2); library(RJDBC); library(gridExtra) 
Sys.setlocale("LC_CTYPE", "chinese") 
o.drv <- JDBC("oracle.jdbc.OracleDriver", classPath="C:/Oracle/instantclient_11_2/ojdbc5.jar", " ") 
o.con <- dbConnect(o.drv, "database_address", "database_user", "database_pw") 

stockcode <- input$stockcode 

x <- dbGetQuery(o.con, "some_query") 

pointLinePlot <- function(df) { 
     plotdata <- gather(df, metric, measure, -reportDate) 
     ggplot() + geom_line(data = plotdata, aes(x = reportDate, y = measure, color = metric)) + 
      geom_point(data = plotdata, aes(x = reportDate, y = measure, color = metric)) + 
      theme(legend.position="bottom", legend.title = element_blank()) + 
      scale_color_manual(name = "", values = c("darkred", "darkgreen", "darkblue", "orange"), 
           breaks = unique(plotdata$metric), labels = unique(plotdata$metric)) 
} 

data_1.1.1 <- data.frame(reportDate = x$REPORT_PERIOD, 
          net_assets_f = x$`TOT_ASSETS-TOT_LIAB`/1E4, 
          monetary_cap_f = x$MONETARY_CAP/1E4, 
          net_cash_f = (x$MONETARY_CAP - x$ST_BORROW)/1E4) 
p1 <- pointLinePlot(data_1.1.1) 
@ 


\begin{figure} 
    \centering 
<<fig = TRUE, echo = FALSE>>= 
print(p1) 
@ 
\caption{Here goes the caption.} 
\label{fig:p1} 
\end{figure} 


\begin{figure} 
    \centering 
<<fig = TRUE, echo = FALSE>>= 
print(grid.table(data_1.1.1, rows = NULL)) 
@ 
\caption{Here goes the caption.} 
\label{fig:p1} 
\end{figure} 


\end{document} 

有什麼辦法打發來自Shin的輸入y直接應用於RMD,就像我在input.Rnw與SWeave(stockcode < - input $ stockcode)?

回答

0

您不必將它傳遞給Rmd文件。渲染Rmd時,變量input$stockcode取自當前環境,就像使用Rnw版本一樣。

server.R

library(knitr) 
library(rmarkdown) 
shinyServer(function(input, output) { 

    output$report = downloadHandler(
    filename = 'myreport.pdf', 
    content = function(file) { 
     out = render('outout.Rmd') 
     file.rename(out, file) # move pdf to file for downloading 
    }, 
    contentType = NA 
) 
}) 

input.Rmd

--- 
title: "Output" 
output: pdf_document 
--- 

# Test 

```{r} 
print(input$stockcode) 
``` 

enter image description here