Почему Shiny-приложение не реагирует на ввод пользователя - PullRequest
0 голосов
/ 05 февраля 2019

Я пытаюсь создать веб-приложение в блестящем, которое учитывало бы различный пользовательский ввод и затем отображало графики / таблицы выходных данных соответственно.Я использую данные ВОЗ о показателях самоубийств, и существует два возможных типа графиков: гистограмма и линейный график.

Пользователю предоставляется выбор между построением графика, на котором ось x представляет собой либо возрастную группу (барплот) или год (линейный график).Им также предоставляется выбор построения графика отдельно для мужчин и женщин, а также для разных стран.

Приведенный ниже код отлично работает для всего, кроме случаев, когда пользователь выбирает x axis = year с помощью gender = 'gender neutral'.Ошибка говорит о том, что рейтинг объекта не найден.Тем не менее, блок кода, который включает в себя скорость объекта, прекрасно работает в других местах.

library(shiny)
library(dplyr)
library(ggplot2)


setwd("C:\\Users\\Lenovoi7\\Shrewsbury School\\IT\\Coursework")

who<-data.frame(read.csv("who.csv",  stringsAsFactors = TRUE))
dput(head(who))
countries<-sort(unique(who$country))
countries<-union(countries, c("World"))
ui<-fluidPage(

  titlePanel("Suicide statistics"),

  sidebarLayout(
  sidebarPanel(

selectInput(
  inputId="x",
  label="Please choose the x variable",
  choices=c("",
            "Age group"="age",
            "Year"="year")),

conditionalPanel(

  condition = "input.x == 'age' || input.x == 'year'",

  selectInput( 

    inputId = "gender",
    label = "Please specify the gender characteristics", 
    choices = c("", "Gender neutral" = "gender_neutral",
                "Gender specific" = "gender_specific"),
    selected = NULL), 

  #nested conditional panel
  #only show this panel if the input is gender_specific

  conditionalPanel(

    condition = "input.gender == 'gender_specific'",

    selectInput(
      inputId = "country",
      label = "Select a country:", 
      choices = countries,
      selected = "Bosnia and Herzegovina")),

  conditionalPanel(

    condition = "input.gender == 'gender_neutral'",

    selectInput(
      inputId = "country",
      label = "Select a country:", 
      choices = countries,
      selected = "Bosnia and Herzegovina")))),

mainPanel(

  plotOutput("graph")


  )))

server <- function(input, output) {

  x<-reactive({input$x})

  gender<-reactive({input$gender})

  country<-reactive({input$country})

  output$graph <- renderPlot(

   #x axis = age group 

   if (x()=="age"){

    if (gender()=="gender_neutral"){

      if (country()=="World"){

      ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no), position="dodge")}

    else {

      #create a new subset of data that will be used??
      who_subset<-subset(who, country == input$country)

      ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no))}}

  else if (gender()=="gender_specific"){

    if (country()=="World"){

      ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}

    else {

      #create a new subset of data that will be used??
      who_subset<-subset(who, country==input$country)

      ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}}}

else if (x()=="year"){

  if (gender()=="gender_neutral"){

    if (country()=="World"){

      who_all <- who %>% 
        group_by(year) %>% 
        summarize(suicides_no = sum(suicides_no),
                  population = sum(population)) %>%
        mutate(rate = 100000 * suicides_no/population)

      ggplot() + 
        geom_line(data = who_all, aes(year, rate))

    }

    else {

      who_subset<-subset(who, country==input$country)

      who_sub_sex <- who_subset %>% 
        group_by(year) %>% 
        summarize(suicides_no = sum(suicides_no),
                  population = sum(population)) %>%
        mutate(rate = 100000 * suicides_no/population)

      ggplot() + 
        geom_line(data = who_subset, aes(year, rate)) 

    }}

  else if (gender()=="gender_specific"){

    if (country()=="World"){

      who_all <- who %>% 
        group_by(year) %>% 
        summarize(suicides_no = sum(suicides_no),
                  population = sum(population)) %>%
        mutate(rate = 100000 * suicides_no/population)

      ggplot() + 
        geom_line(data = who_all, aes(year, rate)) 


    }

    else {

      #create a new subset of data that will be used??
      who_subset<-subset(who, country==input$country)

      who_sub_sex <- who_subset %>% 
        group_by(year, sex) %>% 
        summarize(suicides_no = sum(suicides_no),
                  population = sum(population)) %>%
        mutate(rate = 100000 * suicides_no / population)

          ggplot() + 
            geom_line(data = who_sub_sex, aes(year, rate, color = sex))}

      }

    }
)}

# Create a Shiny app object
shinyApp(ui = ui, server = server)

dput(head(who))  
structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L), 
.Label =   c("Albania", 
"Anguilla", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", 
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Barbados", 
"Belarus", "Belgium", "Belize", "Bermuda", "Bolivia", 
"Bosnia and     Herzegovina", 
"Brazil", "British Virgin Islands", "Brunei Darussalam", "Bulgaria", 
"Cabo Verde", "Canada", "Cayman Islands", "Chile", "Colombia", 
"Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", 
"Denmark", "Dominica", "Dominican Republic", "Ecuador", "Egypt", 
"El Salvador", "Estonia", "Falkland Islands (Malvinas)", "Fiji", 
"Finland", "France", "French Guiana", "Georgia", "Germany", "Greece", 
"Grenada", "Guadeloupe", "Guatemala", "Guyana", "Haiti", "Honduras", 
"Hong Kong SAR", "Hungary", "Iceland", "Iran (Islamic Rep of)", 
"Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", 
"Kazakhstan", "Kiribati", "Kuwait", "Kyrgyzstan", "Latvia", "Lithuania", 
"Luxembourg", "Macau", "Malaysia", "Maldives", "Malta", "Martinique", 
"Mauritius", "Mayotte", "Mexico", "Monaco", "Mongolia", "Montenegro", 
"Montserrat", "Morocco", "Netherlands", "Netherlands Antilles", 
"New Zealand", "Nicaragua", "Norway", "Occupied Palestinian Territory", 
"Oman", "Panama", "Paraguay", "Peru", "Philippines", "Poland", 
"Portugal", "Puerto Rico", "Qatar", "Republic of Korea", 
"Republic of     Moldova", 
"Reunion", "Rodrigues", "Romania", "Russian Federation",
"Saint Kitts and Nevis", 
"Saint Lucia", "Saint Pierre and Miquelon", 
"Saint Vincent and Grenadines", 
"San Marino", "Sao Tome and Principe", "Saudi Arabia", "Serbia", 
"Seychelles", "Singapore", "Slovakia", "Slovenia", "South Africa", 
"Spain", "Sri Lanka", "Suriname", "Sweden", "Switzerland", 
"Syrian Arab Republic", 
"Tajikistan", "TFYR Macedonia", "Thailand", "Trinidad and Tobago", 
"Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", 
"Ukraine", "United Arab Emirates", "United Kingdom", 
"United States of America", 
"Uruguay", "Uzbekistan", "Venezuela (Bolivarian Republic of)", 
"Virgin Islands (USA)", "Zimbabwe"), class = "factor"), 
year = c(1985L, 1985L, 1985L, 1985L, 1985L, 1985L), 
sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L),.
Label = c("female", "male"), class = "factor"), 
age = structure(1:6, .Label = c("15-24 years", "25-34 years", 
"35-54 years", "5-14 years", "55-74 years", "75+ years"),
class  = "factor"), 
suicides_no = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_, 
NA_integer_, NA_integer_), population = c(277900L, 246800L, 
267500L, 298300L, 138700L, 34200L)), 
row.names = c(NA, 6L), class = "data.frame")

Есть ли шанс, что кто-нибудь знает выход из этой проблемы?Я снова хочу, чтобы веб-приложение выводило линейный график, когда пользователь выбирает x axis = year и gender = gender_neutral.

1 Ответ

0 голосов
/ 05 февраля 2019

Попробуйте использовать этот код сервера.

Изменения уже описаны в моих комментариях.Поскольку у меня нет who data.frame, я не смог его протестировать.

server <- function(input, output) {
  output$graph <- renderPlot({
    if (input$x == "age") {
      if (input$gender=="gender_neutral"){
        if (input$country=="World"){
          ggplot(data = who, aes(x = age)) + geom_bar(aes(weights = suicides_no), position="dodge")}
        else {
          #create a new subset of data that will be used??
          who_subset <- subset(who, country == input$country)
          ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no))
        }
      } else if (input$gender=="gender_specific") {
        if (input$country=="World"){
          ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}
        else {
          #create a new subset of data that will be used??
          who_subset <- subset(who, country==input$country)
          ggplot(data = who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")
        }
      }
    } else if (input$x=="year"){
      if (input$gender=="gender_neutral"){
        if (input$country=="World"){
          who_all <- who %>% 
            group_by(year) %>% 
            summarize(suicides_no = sum(suicides_no),
                      population = sum(population)) %>%
            mutate(rate = 100000 * suicides_no/population)
          ggplot() + 
            geom_line(data = who_all, aes(year, rate))
        } else {
          who_subset <- subset(who, country==input$country)
          who_sub_sex <- who_subset %>% 
            group_by(year) %>% 
            summarize(suicides_no = sum(suicides_no),
                      population = sum(population)) %>%
            mutate(rate = 100000 * suicides_no/population)
          ggplot() + 
            geom_line(data = who_sub_sex, aes(year, rate)) 
        }
      } else if (input$gender=="gender_specific"){
        if (input$country=="World"){
          who_all <- who %>% 
            group_by(year) %>% 
            summarize(suicides_no = sum(suicides_no),
                      population = sum(population)) %>%
            mutate(rate = 100000 * suicides_no/population)
          ggplot() + 
            geom_line(data = who_all, aes(year, rate)) 
        } else {
          #create a new subset of data that will be used??
          who_subset <- subset(who, country==input$country)
          who_sub_sex <- who_subset %>% 
            group_by(year, sex) %>% 
            summarize(suicides_no = sum(suicides_no),
                      population = sum(population)) %>%
            mutate(rate = 100000 * suicides_no / population)
          ggplot() + 
            geom_line(data = who_sub_sex, aes(year, rate, color = sex))}
      }
    }
  })
}
...