Rshiny

R Shiny 0. 简介

2021-09-01  本文已影响0人  Jason数据分析生信教室

首先安装shiny包

 install.packages("shiny")

接下来通过运行内嵌的样本函数来看一下shiny到底是个什么东西。

library(shiny)
runExample("01_hello")

Hello Shiny实例’是基于faithful 数据集的直方图,有别于常见的R语言做出的图,特别的有一个可以调整bins(柱的个数)的滑条,用户可以滑动选择bins的数目,app图表会随即产生变化,可以仿造这例子试着做一个属于自己的app。

1. Shiny的基本构成

1.1 用户交互脚本

ui负责控制布局和展示,在源脚本中固定的名称为ui.R,Hello Shiny ui代码都给你准备好了,如下:

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  # Application title
  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )

1.2 服务器脚本

server.R 脚本包含建立app计算机需要的基本说明,Hello Shiny server代码也给你准备好了。

library(shiny)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {

  # Expression that generates a histogram. The expression is
  # wrapped in a call to renderPlot to indicate that:
  #
  #  1) It is "reactive" and therefore should re-execute automatically
  #     when inputs change
  #  2) Its output type is a plot

  output$distPlot <- renderPlot({
    x    <- faithful[, 2]  # Old Faithful Geyser data
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
})

当然, Hello Shiny server.R 非常简单,脚本通过做一些简单的计算,然后根据新的bins的数量再重新画出直方图。
尽管如此,需要注意的是大部分的脚本都是包含在renderplot内部,这个命令上面有一点解释不完善,不理解没关系,不要着急,将来会详细解释这个函数。

2. 运行APP

每个app都有相同的结构即两个脚本(保存在工作目录),这是app的最小结构。

注意: Shiny 支持单文件app,不再需要建立俩个分离的文件server.R and ui.R; 可以创建一个文件叫app,包含服务器和ui两部分,你可以学到更多的关于单文件app的知识,其实不必太在意,因为我们的焦点是用两个文件来建立app。 http://shiny.rstudio.com/articles/single-file.html

建立Shiny app,先做一个工作路径,保存 ui.R 和server.R 文件进去,每个app都要有自己单独的路径。运行shiny app 直接用runapp(“”)命令:

 library(shiny)
 runApp("my_app")

runApp 类似于其他的函数,第一个参数是文件的路径,前提是你的app目录在你的工作路径下面,在这种情况下,文件名就是路径名即可。

其他

rshiny包里还包含了很多别的例子,有兴趣可以操作一下看看。
每一个例子都有source code,有时间值得细细品味。

system.file("examples", package="shiny")

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
上一篇 下一篇

猜你喜欢

热点阅读