shiny 初级


1. 简介shiny


什么是shiny:


Shiny 是一个开源的 R 包,它为使用 R 构建 Web 应用提供了一个优雅有力的 Web 框架.


shiny的特点


  1. 不需要R用户了解前端,后端知识
  2. 不需要R用户了解网页开发语言的知识,比如javascript
  3. 为R用户量身打造,帮助R用户高效的开发web程序


学习本课程的背景知识


  1. 有一定R语言基础


学习完本课程,同学们会有什么收获


学完本课程,同学会了解shiny的工作原理,并且能够自己开发一个shiny 程序


案例展示


案例

案例


同学们可以通过这个链接查看我制作的一个shiny案例。

https://liam.shinyapps.io/dashboard/


这个案例是一个推荐系统,可以帮助店铺找到某一个商品相似的商品,以及可能对这个商品感兴趣的人。


另外还对商品以及店铺进行了数据分析,并展示


2. shiny app 的基本部分


从这里开始,我们会开始学习shiny的基本原理,我们会学习到

  1. shiny 原程序的组成部分,分为UI和Server
  2. shiny程序内有哪些元素 :小部件,render函数,input,output
  3. input 和output之间的关系


2.1 案例1


我们现来查看一个例子,然后分析其工作原理:


打开案例

library(shiny)
runExample("01_hello")
example1

example1


这个例子使用的是自带的faithful数据集合,通过改变slider滑块的值调整直方图的bin。


shiny程序包含两个部分:UI部分和server部分,简单来说,

  1. UI 部分就是我们需要设定web页面要怎么展示
  2. Server 部分就是后台的计算是如何进行


我们来看一下上面这个程序的源代码:


首先是UI部分:


ui <- fluidPage( 
  
  # App title ----
  titlePanel("Hello Shiny!"),
  
  # 这里指定的是什么布局方式
  sidebarLayout(
    
    # Sidebar panel  
    sidebarPanel(
      
      # 这里是定义一个slider 作为输入
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
      
    ),
    
    # 主页面,这里主页面是一个绘图
    mainPanel(
      
      # Output: Histogram ----
      plotOutput(outputId = "distPlot")
      
    )
  )
)
  • sidebarLayout 边栏布局,是页面布局,这里使用的的是默认的页面布局,此布局为输入提供了侧栏,sidebarPanel,为输出提供了大的主区域,mainPanel

  • sliderInput 是一个部件,用于提供输入

  • plotOutput(outputId = “distPlot”) 是输出,输出一个图


然后是Server部分


定义我们UI部分展示的结果是如何计算的


server <- function(input, output) {
  

  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")
    
  })
  
}


生成app


shinyApp(ui, server)


总结


shiny 程序分为两个部分 ,UI和Server


  1. UI ,UI定义了页面的布局
  2. UI里面包含的元素有,页面布局,部件,输出
  3. Server ,Server定义了页面背后的计算
  4. Server,中来来自页面的输入通过input进行表示,输出页面通过output表示


2.2 第二个例子


这个例子展示了直接打印R对象,以及使用HTML表格显示数据


运行下列代码,打开第二个例子:

library(shiny)
runExample("02_text")
shinyexample2

shinyexample2


通过这个例子我们来学习UI和server之间是如何建立联系的。


我们来查看一下代码:


UI部分


# Define UI for dataset viewer app ----
ui <- fluidPage(
  
  # App title ----
  titlePanel("Shiny Text"), # 标题
  
  # Sidebar layout with a input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      # Input: Selector for choosing dataset ----
      selectInput(inputId = "dataset",
                  label = "Choose a dataset:",
                  choices = c("rock", "pressure", "cars")), # 这是一个选择输入
      
      # Input: Numeric entry for number of obs to view ----
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10) # 这是一个数字输入
    ),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      # Output: Verbatim text for data summary ----
      verbatimTextOutput("summary"), # 这是一个输入
      
      # Output: HTML table with requested number of observations ----
      tableOutput("view") # 这是一个表格输入
      
    )
  )
)


我们可以看到


  1. 页面布局是默认的布局,边栏布局
  2. UI中有两个部件selectInput和numericInput,选择输入和数字输入
  3. 有两个输出: verbatimTextOutput(“summary”),tableOutput(“view”),这两个输出对应的ID分别是“summary”和“view”


两个UI部件selectInput和numericInput,这两个部件的ID分别是dataset 和obs


Server


 #Define server logic to summarize and view selected dataset ----
server <- function(input, output) {
  
  # Return the requested dataset ----
  datasetInput <- reactive({ # 输入
    switch(input$dataset,
           "rock" = rock, # 对应了不同的数据集合
           "pressure" = pressure,
           "cars" = cars)
  })
  
  # Generate a summary of the dataset ----
  output$summary <- renderPrint({ # 输出一个summary,这是一个R对象
    dataset <- datasetInput()
    summary(dataset)
  })
  
  # Show the first "n" observations ----
  output$view <- renderTable({ # 另外一个输出
    head(datasetInput(), n = input$obs)
  })
  
}


输入:

  1. UI中selectInput部件对应的数据为input$dataset
  2. UI中numericInput部件对应的数据为input$obs


输出: 1.verbatimTextOutput(“summary”),server中对应的是output\(summary 2. tableOutput("view"),server中对应的是output\)view


render函数

1.输出通过render函数进行传递,举例而言,renderPrint将summary(dataset)赋值给了output\(summary 2. renderTable将head(datasetInput(), n = input\)obs)的 结果为赋值给了output$view


总结:

  1. UI中的元素都存在一个ID,server通过\(ID进行提取,例如, input\)obs或则 output$summary
  2. 输出通过render函数进行传递


3. shiny 总结


回顾我们课程,我们是如何实现一个shiny的web程序:

  1. 程序分为两个部分,UI和server
  2. UI定义我们的网页是如何展示的,server定义后台是如何运算的
  3. UI中有哪些输出函数
UI部分 server部分
dataTableOutput renderDataTable
imageOutput renderImage
plotOutput renderPlot
verbatimTextOutput renderPrint
tableOutput renderTable
textOutput renderText
uiOutput renderUI
htmloutput renderUI


  1. UI中有哪些输入函数


4. 制作一个shiny


打开Rstudio,点击file,创建一个shiny app

使用的数据数据是,ggplot里面自带的数据diamonds,绘制不同的直方图:



#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- fluidPage(
   
   # Application title
   titlePanel("Diamond data"),
   
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
        selectInput(inputId = "x",label = 'x',choices = names(diamonds)[c(1,5,6,7,8,9,10)],
                    selected = T),
        selectInput(inputId = "y",label = 'y',choices = names(diamonds)[c(1,5,6,7,8,9,10)],
                    selected = T)
      ),
      
      
      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("diamondplot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   
   output$diamondplot <- renderPlot({
      # generate bins based on input$bins from ui.R
    plot(x = diamonds[[input$x]],y = diamonds[[input$y]],xlab = 'x',ylab = 'y')
     
   })
}

# Run the application 
shinyApp(ui = ui, server = server)


5. shiny部署


有几种方式: 1. Shinyapps.io 2. Shiny server 3. Shiny Server Pro 4. Rstudio Connect


本课程介绍使用Shinyapps.io进行shiny部署,选择Shinyapps.io将应用程序部署到Web,不需要自己的服务器,只需要简单的代码,就可以轻松的部署到Web


  1. 首先要注册,有github账户也可以使用github账户进行注册

  2. 下载rsconnect包

    install.packages('rsconnect’)
    library(rsconnect)
  3. 登陆:http://www.shinyapps.io/


进行shiny配置

然后在Rstudio中运行

  1. 编写好shiny app 之后,进行部署
library(rsconnect)
deployApp()


资源


  1. https://pan.baidu.com/s/1xquGy9IbAOWIQGAEw2wCDw

  2. https://pan.baidu.com/s/1Yo2nk1c7ErMeAXe61Bo_1Q