Shiny包的特点在于不需要了解网页语言,可以用纯R来搭建。生成的网页应用是动态交互,而且是即时更新的。Shiny还提供了现成组件方便快速在网页上展示数据、图表和模型,的确是非常的炫。
首先安装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会自动打开系统默认的浏览器,并展示出如下的界面。
Shiny包的缺点:在部署分享方面,Shiny包只能在本地浏览器展示应用。如果要分享给其它人的话,需要将R代码传到网盘或打包分发,而对方也需要使用runApp命令来进行本地展示。RStudio团队正在开发Shiny服务器构架,让使用者仅需要一个浏览器和网址就可以运行网页应用。不过这将是一个收费的服务。