Lecture4_my-script-with-R_shiny

Jimmyjmzeng1314@outlook.com

Keywords: shiny/html

source code :https://github.com/rstudio/shiny

Official website: http://shiny.rstudio.com/

R-blog http://www.r-bloggers.com/search/shiny

YouTubehttps://www.youtube.com/watch?v=_0ORRJqctHE

many example : http://shinyapps.org/

book : http://www.amazon.com/Web-Application-Development-Using-Shiny/dp/1783284471

官方教程:http://rstudio.github.io/shiny/tutorial/#

除了安装shiny包的时候自带了11个例子 ,在Documents\R\win-library\3.2\shiny\examples\01_hello

github上面还有非常多的例子https://github.com/rstudio/shiny-examples

这些github的例子,都是可以通过网页来访问的:https://github.com/rstudio/shiny-examples/blob/master/gallery-URLs.txt

我们可以运行本地的shiny app,也可以运行网页版的,也可以直接用网页浏览器来访问,也可以直接运行githubapphttp://shiny.rstudio.com/tutorial/lesson7/

如果想要制作复杂的网页,就需要有多个网页互相链接起来,就需要懂UI的格式了

  tags$div(class="header", checked=NA,
               tags$p("Ready to take the Shiny tutorial? If so"),
               tags$a(href="shiny.rstudio.com/tutorial", "Click Here!")
      )

上面这个例子,就可以在一个网页中链接另一个shiny app

useful links :http://shiny.rstudio.com/articles/html-tags.html

http://shiny.rstudio.com/articles/html-ui.html

http://shiny.rstudio.com/articles/tag-glossary.html

还有非常多的文章来描述如何制作shiny app的:http://shiny.rstudio.com/articles/

Shiny包学习笔记

Example 1

页面左右布局,左边是一个滑动杆,右边是一幅图。

效果如下

客户端界面代码

library(shiny)

shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),

sidebarLayout(

    sidebarPanel(

      sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30)),

      mainPanel(plotOutput("distPlot")))

))

服务端程序代码

library(shiny)

shinyServer(function(input, output) {

  output$distPlot <- renderPlot({

    x<- faithful[, 2] #数据是系统自带的

    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = 'darkgray', border = 'white') })})

Example 2

页面左右布局,左边是一个复选框和一个数字输入框,右边显示文字框和表格。

实现效果如下

客户端代码如下

library(shiny)

library(datasets)

shinyServer(function(input, output) {

  datasetInput <- reactive({

    switch(input$dataset,     #这个是UI端口的输入输入变量,复选框的内容

           "rock" = rock,

           "pressure" = pressure,

           "cars" = cars)

  })

  output$summary <- renderPrint({

    dataset <- datasetInput()  #用户在UI界面选择了复选框的内容就会在这里进行处理

    summary(dataset)

  })

  output$view <- renderTable({

    head(datasetInput(), n = input$obs) #这个obs变量也是用户在UI界面输入的变量

  })

})

Example 3

页面布局,与第二个相比,多了一个

library(shiny)

shinyUI(fluidPage(

  titlePanel("Reactivity"),

  sidebarLayout(

    sidebarPanel(

      textInput("caption", "Caption:", "Data Summary"),

      selectInput("dataset", "Choose a dataset:",

                  choices = c("rock", "pressure", "cars")),

      numericInput("obs", "Number of observations to view:", 10)

    ),

    mainPanel(

      h3(textOutput("caption", container = span)),     

      verbatimTextOutput("summary"),

      tableOutput("view")

    )

  )

))

fluidPage(..., title = NULL, responsive = TRUE, theme = NULL)

sidebarLayout(sidebarPanel, mainPanel, position = c("left", "right"),

  fluid = TRUE)

textInput(inputId, label, value = "")

selectInput(inputId, label, choices, selected = NULL, multiple = FALSE,

  selectize = TRUE, width = NULL)

selectizeInput(inputId, ..., options = NULL, width = NULL)

numericInput(inputId, label, value, min = NA, max = NA, step = NA)

shinyUI(pageWithSidebar(headerPanel("Miles Per Gallon"),sidebarPanel(), mainPanel()))
library(shiny)

library(datasets)

shinyServer(function(input, output) {

  datasetInput <- reactive({       #这个变量是需要在服务端执行才能获取UI端的输入

    switch(input$dataset,

           "rock" = rock,

           "pressure" = pressure,

           "cars" = cars)

  })

  output$caption <- renderText({

    input$caption

  })

  output$summary <- renderPrint({

    dataset <- datasetInput()

    summary(dataset)

  })

  output$view <- renderTable({

    head(datasetInput(), n = input$obs)

  })

})

其中涉及到的函数如下

reactive(x, env = parent.frame(), quoted = FALSE, label = NULL,

  domain = getDefaultReactiveDomain())

renderText(expr, env = parent.frame(), quoted = FALSE, func = NULL)

renderTable(expr, ..., env = parent.frame(), quoted = FALSE, func = NULL)

renderPrint(expr, env = parent.frame(), quoted = FALSE, func = NULL,

  width = getOption("width"))

一系列函数都可以show出来的


Example 4

library(shiny)

library(datasets)

mpgData <- mtcars#从系统中挑选自己想表现的数据

mpgData$am <- factor(mpgData$am, labels = c("Automatic", "Manual"))

#把我们的数据中的am变量因子化为

shinyServer(function(input, output) {

  formulaText <- reactive({

    paste("mpg ~", input$variable)#这里接受我们UI端用户的选择变量

  })

  output$caption <- renderText({ #在右边输出字符串

    formulaText()

  })

  output$mpgPlot <- renderPlot({  #在右边画箱线图

    boxplot(as.formula(formulaText()),

            data = mpgData,

            outline = input$outliers) #设置是否显示离群点,又UI端用户传入变量

  })

})

Boxplot这个函数可以接受一个参数就是formulaa formula, such as y ~ grp, where y is a numeric vector of data values to be split into groups according to the grouping variable grp (usually a factor).这样就指定了某个数据集里面的某两个变量来做boxplot,非常方便

 

checkboxInput(inputId, label, value = FALSE)

checkboxInput("outliers", "Show outliers", FALSE)

 

 


Example 5

服务端

 

 

 

 

 

UI

This example demonstrates Shiny's versatile sliderInput widget.

Slider inputs can be used to select single values, to select a continuous range of values, and even to animate over a range.

sliderInput(inputId, label, min, max, value, step = NULL, round = FALSE, format = "#,##0.#####", locale = "us", ticks = TRUE, animate = FALSE,width = NULL)

label是显示在用户界面上给用户看的文字

inputId是用户在该控件什么选取的值,变量名


Example 6

这个UI界面左边还是sidebarPanel(),里面有两个控件,即radioButtons
sliderInput
但是右边的界面,改版了,之前只是mainPanel里面竖着罗列几个输出控件
tableOutputplotOutputverbatimTextOutput,但是这次是

 
所以UI界面的效果如下,右边的输出控件被放在菜单栏里面了,而不是简简单单的全部显示出来

UI端需要用户传入的变量是input$n input$$dist

 

 

 

 

其中服务端的程序还是写函数接收radioButtonssliderInput控件中用户传入的变量

把用户传入的变量组合成一个data,第一个元素是概率分布的名称,第二个元素是用户选择的n值组合成的分布数据

 


Example 7

对比上面那个就增加了一个submit控件,只有提交了用户在UI上面的选择之后才会进行重新刷新显示页面

UI端很简单,继续在siderbarPanel里面罗列控件即可

有了submitButton控件之后,reactive变量就会默认等待submit提交之后才进行


Example 8

这个没有UI界面,而是一个index.html,后面的服务端还是差不多的

UI端换成网页端之后,要用html语言来写这些控件

 

可以简单对比一下

也可以跟之前的第五个例子做对比

 

Example 9

设计了一些控件,这样用户可以自行上传资料

服务端只有一个renderTable就是显示我们读取的表格,renderTable把读入的文件处理成数据格式,然后丢给tableOutput来显示在界面上

直接在界面显示了,UI端口的函数就是选择文件,

fileInput(inputId, label, multiple = FALSE, accept = NULL)

 


Example 10

downloadButton(outputId, label = "Download", class = NULL)

downloadLink(outputId, label = "Download", class = NULL)

 

downloadButton('downloadData', 'Download') #UI端设置这个按钮
然后在服务端设置数据下载的方式


Example 11

UI端界面很简单,就是把当前时间显示处理,时间变量来自于服务端

服务端把当前世界做成renderText

 

 

What is Reactivity?

The Shiny web framework is fundamentally about making it easy to wire up input values from a web page, making them easily available to you in R, and have the results of your R code be written as output values back out to the web page.

input values => R code => output values

Since Shiny web apps are interactive, the input values can change at any time, and the output values need to be updated immediately to reflect those changes.

界面内容需实时更新

UI端设置好如下控件,用户在选择框里面选择的内容需要实时更新到input变量

在服务端写一个reactivity来接受用户选择

 


Example 12

以上例子都是左右布局的,左边是给用户选择的界面,右边是展示给用户的数据图形

服务端程序主要是根据用户的input来构建好output用以输出

这个滑动块只有在input控件里面的denstity控件在被选择了true才会显示在UI界面上面