Shiny是一個R軟件包,可很方便的從R直接構(gòu)建交互式Web應(yīng)用程序。
首先是安裝Shiny軟件包
install.packages("shiny")
Shiny有11個內(nèi)置的演示例子來講解Shiny的工作流程,如01_hello:
library(shiny)
#直接展示內(nèi)置的實(shí)例
runExample("01_hello")

這個直方圖在左側(cè)有一個可以調(diào)整bins個數(shù)的滑條,當(dāng)用戶滑動選擇bins的數(shù)目時,圖表也隨即產(chǎn)生變化,這樣實(shí)現(xiàn)了一個交互式的過程。
Shiny apps的構(gòu)成
Shiny apps包含一個R script即app.R,位于某個目錄下如(newdir/),app可以通過函數(shù)runApp("newdir/app.R")運(yùn)行。
app.R 包括三部分:
1.a user interface object
2.a server function
3.a call to the shinyApp function
即:1.用戶界面(ui)object 控制應(yīng)用程序的布局和外觀。2.server function包含構(gòu)建應(yīng)用程序所需的說明。3.最后,shinyApp function通過ui和server創(chuàng)建Shiny應(yīng)用程序?qū)ο蟆?/p>
以Hello Shiny為例
1.ui:(Hello Shiny示例的ui對象)
library(shiny)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
2.server:(Hello Shiny示例的server功能)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
3.shinyApp:最后運(yùn)行時用shinyApp將ui和server結(jié)合
shinyApp(ui = ui, server = server)

Shiny App的保存
每個Shiny應(yīng)用程序都具有相同的結(jié)構(gòu):app.R包含ui和的文件server??梢酝ㄟ^創(chuàng)建新目錄并在其中保存app.R文件來創(chuàng)建Shiny應(yīng)用程序。
如:將ui,sever,runApp這三部分代碼保存test/App目錄下的testApp.R里。
為了與之前的代碼區(qū)分,我改了一下顏色和title,保存后,重新運(yùn)行
runApp("/test/App/testApp.R")

歡迎關(guān)注!