Shiny包的特點在于不需要了解網(wǎng)頁語言狗唉,可以用純R來搭建侣滩。生成的網(wǎng)頁應用是動態(tài)交互,而且是即時更新的变擒。Shiny還提供了現(xiàn)成組件方便快速在網(wǎng)頁上展示數(shù)據(jù)君珠、圖表和模型,的確是非常的炫娇斑。
首先安裝Shiny包:
options(repos = c(RStudio = 'http://rstudio.org/_packages', getOption('repos')))
install.packages('shiny')
install.packages('digest')
install.packages('htmltools')
install.packages('httpuv')
再寫兩個R代碼文件:一個是負責前端的ui.R策添,另一個是負責后端的server.R材部。
library(httpuv)
library(htmltools)
library(digest)
library(shiny)
library(ggplot2)
shinyUI(bootstrapPage(
selectInput(inputId = "n_breaks",
label = "Number of bins in histogram (approximate):",
choices = c(10, 20, 35, 50),
selected = 20),
checkboxInput(inputId = "individual_obs",
label = strong("Show individual observations"),
value = FALSE),
checkboxInput(inputId = "density",
label = strong("Show density estimate"),
value = FALSE),
plotOutput(outputId = "main_plot", height = "300px"),
# Display this only if the density is shown
conditionalPanel(condition = "input.density == true",
sliderInput(inputId = "bw_adjust",
label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
))
server.R的代碼如下:
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
output$main_plot <- renderPlot({
hist(faithful$eruptions,
probability = TRUE,
breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)",
main = "Geyser eruption duration")
if (input$individual_obs) {
rug(faithful$eruptions)
}
if (input$density) {
dens <- density(faithful$eruptions,
adjust = input$bw_adjust)
lines(dens, col = "blue")
}
})
})
將這兩個代碼文件存放到同一個文件夾下,例如我是放在在"C:/Users/cdas3/Documents/R/R-program/shiny-app"唯竹。最后在控制臺下運行:
library(shiny)
runApp("C:/Users/cdas3/Documents/R/R-program/shiny-app")
之后R會自動打開系統(tǒng)默認的瀏覽器乐导,并展示出如下的界面。
Shiny包的缺點:在部署分享方面浸颓,Shiny包只能在本地瀏覽器展示應用物臂。如果要分享給其它人的話,需要將R代碼傳到網(wǎng)盤或打包分發(fā)产上,而對方也需要使用runApp命令來進行本地展示棵磷。RStudio團隊正在開發(fā)Shiny服務器構(gòu)架,讓使用者僅需要一個瀏覽器和網(wǎng)址就可以運行網(wǎng)頁應用晋涣。不過這將是一個收費的服務仪媒。