shiny入门实践——Hello Shiny—科研工具箱

请关注公众号【叨客学习资料】 在使用网站的过程中有疑问,请来公众号进行反馈哦
Shiny是一个R软件包,可很方便的从R直接构建交互式Web应用程序。

安装Shiny软件包

install.packages(\"shiny\")

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

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

图片[1]-shiny入门实践——Hello Shiny—科研工具箱-叨客学习资料网

这个直方图在左侧有一个可以调整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)


图片[2]-shiny入门实践——Hello Shiny—科研工具箱-叨客学习资料网

Shiny App的保存

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

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

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

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

图片[3]-shiny入门实践——Hello Shiny—科研工具箱-叨客学习资料网

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
请输入有效评论哦,肆意灌水或者乱打评论是不会通过的,会影响您评论后获得资源哦~~
提交
头像

昵称

取消
昵称表情

    暂无评论内容