shiny入门课【1.简介】

2019-06-16 13:06:04 浏览数 (1)

shiny是一个R包,用于创建交互式web应用,首先需要安装这个包。

代码语言:javascript复制
install.packages("shiny")

shiny包内置了11个已经写好的应用,我们可以使用runExample命令来运行。

代码语言:javascript复制
library(shiny)
runExample("01_hello")

Shiny应用的结构

shiny应用一般单独存放在app.R代码文件中,如果app.R 放置于newdir/目录下面,那应用就可以用runExample("newdir")来运行。

app.R包括以下三个部分:

  • ui 对象
  • server函数
  • 对shinyApp函数的调用 ui对象控制了页面布局以及应用的外观,server用于控制交互,shinyApp函数用于创建shiny应用。

ui对象示例:

代码语言:javascript复制
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")

    )
  )
)

server函数示例:

代码语言:javascript复制
# 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")

    })

}

整体结构

代码语言:javascript复制
library(shiny)

# See above for the definitions of ui and server
ui <- ...

server <- ...

shinyApp(ui = ui, server = server)

运行应用

将目录名传递给runApp即可。

代码语言:javascript复制
library(shiny)
runApp("my_app")

Shiny内置应用

代码语言:javascript复制
runExample("01_hello")      # a histogram
runExample("02_text")       # tables and data frames
runExample("03_reactivity") # a reactive expression
runExample("04_mpg")        # global variables
runExample("05_sliders")    # slider bars
runExample("06_tabsets")    # tabbed panels
runExample("07_widgets")    # help text and submit buttons
runExample("08_html")       # Shiny app built from HTML
runExample("09_upload")     # file upload wizard
runExample("10_download")   # file download wizard
runExample("11_timer")      # an automated timer

0 人点赞