R语言学习之Shiny入门

2021-02-27  本文已影响0人  R语言数据分析指南

Shiny是一个R程序包,它有助于使用R代码创建交互式Web应用程序,该代码可以在本地也可以在自己的服务器上托管。shiny可以从极其简单到极其复杂。在其众多用途中,Shiny是与他人进行数据互动的绝佳方法,本文通过一个示例先来简单介绍一下Shiny

安装Shiny软件包

install.packages("shiny")
library(shiny)

Shiny附带了一组内置示例,可以使用runExample( )函数来查看示例

runExample("01_hello")

本示例是一个带有滑块的直方图示例,用于控制箱的大小。该代码也显示在示例中

运行下方代码查看更多的示例

runExample("02_text")
runExample("03_reactivity")
runExample("04_mpg")
runExample("05_sliders")
runExample("06_tabsets")
runExample("07_widgets")
runExample("08_html")
runExample("09_upload")
runExample("11_timer")

在RStudio中转到File -> New File -> Shiny Web App选择一个文件Web应用程序,将看到如下代码

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   
   # Application title
   titlePanel("Old Faithful Geyser Data"),
   
   # Sidebar with a slider input for 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")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   
   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2] 
      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')
   })
}
# Run the application 
shinyApp(ui = ui, server = server)

Shiny将其应用程序的功能分为三个不同的部分:

第一部分
ui <- fluidPage()
第二部分
server <- function(input, output) {}
第三部分
shinyApp(ui = ui, server = server)

下面通过一个例子来展示

library(shiny)
library(shinyWidgets)
library(dslabs)
library(tidyverse)
library(plotly)


data("us_contagious_diseases")
disease <- us_contagious_diseases
disease <- mutate(disease, percapita = count/(population/100000)) %>% 
    pivot_longer(cols = c(count, percapita), 
                 names_to = "data", values_to = "value")

ui <- fluidPage(
    
    titlePanel("Diseases in the US 1928-2011"),
    sidebarLayout(
        sidebarPanel(
            # inputs
# selectizeInput()所有状态名称创建一个下拉菜单
            selectizeInput("stateInput", "State",
                           choices = unique(disease$state),  
                           selected="Virginia", multiple =FALSE), 
# checkboxGroupInput()来创建复选框
            checkboxGroupInput("diseaseInput", "Disease",
                               choices = c("Hepatitis A",
                                           "Measles",
                                           "Mumps", "Pertussis",
                                           "Polio", "Rubella", 
                                           "Smallpox"),
                               selected = c("Hepatitis A", "Polio")),
# sliderInput()创建可以滑动的刻度条
            sliderInput("yearInput", "Year", min=1928, max=2011, 
                        value=c(1928, 2011), sep=""),
            radioGroupButtons("dataInput", "Data",
                              choiceNames = list("Count", "Per capita"),
                              choiceValues = list("count", "percapita"))
        ),  
        
        mainPanel(
            plotOutput("diseaseplot"),
            br(), br(),
            verbatimTextOutput("stats"), 
            br(), br(),
            plotlyOutput("distplot")
        ) 
    )   
)   

server <- function(input, output) {
    
    d <- reactive({
        disease %>%
            filter(state == input$stateInput,
                   disease %in% input$diseaseInput,
                   year >= input$yearInput[1],
                   year <= input$yearInput[2],
                   data == input$dataInput)
    }) 
    
    
    output$diseaseplot <- renderPlot({
        
        ggplot(d(), aes(x=year, y = value, color=disease)) +
            geom_line() + 
            theme_bw() +
            xlab("Year") +
            ylab(input$dataInput) +
            ggtitle("Cases over time")
    })
    
    output$stats <- renderPrint({
        
        aggregate(value ~ disease, data = d(), sum)
        
    })
    
    output$distplot <- renderPlotly({
        
        box <- plot_ly(d(), y = ~value,
                       color = ~disease, type = "box")  %>%
            layout(title = "Distribution of cases over different years",
                   yaxis = list(title=input$dataInput))
        
    })
    
}

shinyApp(ui=ui, server=server)

可以看到要完全掌握Shiny进行交互式数据分析还是有一定难度的,上面所列的11个示例数据希望对大家有所帮助

上一篇 下一篇

猜你喜欢

热点阅读