Posted on
Shiny是一个R软件包,可很方便的从R直接构建交互式Web应用程序。

安装Shiny软件包

install.packages("shiny")

Shiny有11个内置的演示例子来讲解Shiny的工作流程,如01_hello:

library(shiny)#直接展示内置的实例runExample("01_hello")

这个直方图在左侧有一个可以调整bins个数的滑条,当用户滑动选择bins的数目时,图表也随即产生变化,这样实现了一个交互式的过程。

Shiny apps的构成

Shiny apps包含一个R script即app.R,位于某个目录下如(newdir/),app可以通过函数runApp(“newdir/app.R”)运行。

app.R 包括三部分:

1.a user interface object

2.a server function

3.a call to the shinyApp function

即:1.用户界面(ui)object 控制应用程序的布局和外观。2.server function包含构建应用程序所需的说明。3.最后,shinyApp function通过ui和server创建Shiny应用程序对象。

(以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:最后运行时用shinyApp将ui和server结合

shinyApp(ui = ui, server = server)


Shiny App的保存

每个Shiny应用程序都具有相同的结构:app.R包含ui和的文件server。可以通过创建新目录并在其中保存app.R文件来创建Shiny应用程序。

如:将ui,sever,runApp这三部分代码保存test/App目录下的testApp.R里。

为了与之前的代码区分,我改了一下颜色和title,保存后,重新运行:

runApp("/test/App/testApp.R")

发表评论

邮箱地址不会被公开。 必填项已用*标注