0

This if my first shiny app, I've been trying to debug for a couple of days - I'm attempting to create a shiny app that shows state mortality rate against the national average using a line graph. Whenever I run the app the UI blinks and the page goes blank. I do get 2 error messages. Any suggested will be much appreciated

ui.R

library(shiny)
url < "https://raw.githubusercontent.com/indianspice/IS608/master/Assign3/cleaned-cdc-mortality-1999-2010-2.csv"
mdata <- read.csv(url, stringsAsFactors = FALSE)

#Extract unique states and disease
states <- unique(mdata$State)
causes <- unique(mdata$ICD.Chapter)

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

  #Application title
  titlePanel("Mortality Improvement by State"),

  #Dropdown state and cause
      sidebarLayout(
        sidebarPanel(selectInput("state_name", "State:", choices = states)
             , radioButtons("cause_name", "Select disease - cause of Death:",
                                c("Infectious & parasitic" = "Certain infectious and parasitic diseases"    , 
                              "Neoplasms" = "Neoplasms",
                              "Blood & blood-forming & immune mechanism disorders" = "Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism",
                              "Endocrine, nutritional & metabolic" = "Endocrine, nutritional and metabolic diseases",
                              "Mental & behavioural disorders" = "Mental and behavioural disorders",
                              "Nervous system" = "Diseases of the nervous system",
                              "Ear & mastoid process" = "Diseases of the ear and mastoid process",
                              "Circulatory system"  = "Diseases of the circulatory system",
                              "Respiratory system" = "Diseases of the respiratory system",
                              "Digestive system" = "Diseases of the digestive system",
                              "Skin & subcutaneous tissue" = "Diseases of the skin and subcutaneous tissue",
                              "Musculoskeletal system & connective tissue" = "Diseases of the musculoskeletal system and connective tissue",
                              "Genitourinary system" = "Diseases of the genitourinary system",
                              "Pregnancy, childbirth & the puerperium" = "Pregnancy, childbirth and the puerperium",
                              "Conditions originating in the perinatal period" = "Certain conditions originating in the perinatal period",
                              "Congenital malformations, deformations & chromosomal abnormalities" = "Congenital malformations, deformations and chromosomal abnormalities",
                              "Symptoms, signs & abnormal clinical & laboratory findings, not classified" = "Symptoms, signs and abnormal clinical and laboratory findings, not elsewhere classified",
                              "External causes of morbidity & mortality" = "External causes of morbidity and mortality"))
   ),

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

server.R

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

#Number per 50000
crude_rate <- 500000
url < "https://raw.githubusercontent.com/indianspice/IS608/master/Assign3/cleaned-cdc-mortality-1999-2010-2.csv"
mdata <- read.csv(url, stringsAsFactors = FALSE)

#Extract unique states and disease
#states <- unique(mdata$State) - remove
#causes <- unique(mdata$ICD.Chapter) remove

nat_cause <- aggregate(cbind(Deaths, Population) ~ ICD.Chapter + Year, mdata, FUN=sum)
#Add national average column
nat_cause$NatAvge <- round(nat_cause$Deaths / nat_cause$Population * crude_rate, 4)

#Define server logic required to visulaize the data
shinyServer(function(input, output, session) {

sub_mdata <- reactive({
        paste("Cause of Death: ", input$causes)
  
    
    output$caption <- renderText({
        print(input$causes)
        sub_mdata()
    })
    
sub_mdata <- reactive({
    subset(mdata, ICD.Chapter == input$causes & State == input$states,
           select=c(Year, Crude.Rate, ICD.Chapter))
})

new_df <- reactive({
    df <- sub_mdata()
    colnames(df) <- c("Year", "Rate_State", "ICD.Chapter")
    df <- merge(df, nat_cause, by=c("Year", "ICD.Chapter"))
    df = dplyr::mutate(df, state_diff = lag(Rate_State) - Rate_State)
    df = dplyr::mutate(df, nat_diff = lag(NatAvge) - NatAvge)
    df = dplyr::mutate(df, st_nat = (state_diff - nat_diff))
    return(df)
})

})

output$causev <- renderPlot({
    
    p <- ggplot(data=new_df(), aes(x="Year", y="st_nat")) +
        geom_line()
    print(p)
})
})

Error

Warning: Error in get: object 'FUN' of mode 'function' was not found
Stack trace (innermost first):
    46: get
    45: match.fun
    44: aggregate.data.frame
    43: aggregate.formula
    42: aggregate
     1: runApp
Error in get(as.character(FUN), mode = "function", envir = envir) : 
object 'FUN' of mode 'function' was not found

Data

                           ICD.Chapter        State Year Deaths Population Crude.Rate
1 Certain infectious and parasitic diseases    AL 1999   1092    4430141       24.6
2 Certain infectious and parasitic diseases    AL 2000   1188    4447100       26.7
3 Certain infectious and parasitic diseases    AL 2001   1211    4467634       27.1
4 Certain infectious and parasitic diseases    AL 2002   1215    4480089       27.1
5 Certain infectious and parasitic diseases    AL 2003   1350    4503491       30.0
6 Certain infectious and parasitic diseases    AL 2004   1251    4530729       27.6
Community
  • 1
  • 1
Sharon M
  • 194
  • 5
  • 15
  • I'm pretty sure the arguments for `ggplot` should be unquoted. Have you tried `ggplot(data=new_df(), aes(x=Year, y=st_nat))`? – Gregor de Cillia Oct 06 '17 at 02:49
  • Another possible problem is you might have a name collusion with `stats::df`. See [here](https://stackoverflow.com/questions/21367922/error-in-getas-characterfun-mode-function-envir-envir) – Gregor de Cillia Oct 06 '17 at 02:54
  • @GregordeCillia I removed the quotes but I'm getting the same error messages – Sharon M Oct 06 '17 at 03:01
  • Have you tried bypassing the possible collusion? – Gregor de Cillia Oct 06 '17 at 03:03
  • There are lots of issues in your test example. `new_df` was not visible in the `output$causev` scope. The object `states` does not exist, `url < "https://raw..."` is not valid (did you mean to assign?). Please rewrite this code and make sure it works in a clean session. – Gregor de Cillia Oct 06 '17 at 03:33
  • @GregordeCillia, It did not work. I.m getting the same error messages that I added to the post. url <- "https://raw is assigned to mdata – Sharon M Oct 06 '17 at 23:20
  • I assume you are referring to my answer, not my comment? Try running the fist lines (everything before `server <-`). Do you still get the same error? – Gregor de Cillia Oct 07 '17 at 01:44
  • @GregordeCillia Thanks for your help. I decided to use a different approach that worked. I just couldn't debug this. – Sharon M Oct 08 '17 at 20:35

1 Answers1

0

Does the following code work for you? I basically just took the example you gave and removed some small errors. Did never get the Warning: Error in get: ... message tough.

NOTE: Make sure to run this code in a clean session. The reason for your error might be a name collision. See here.

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

url <- paste0("https://raw.githubusercontent.com/indianspice/IS608/",
              "master/Assign3/cleaned-cdc-mortality-1999-2010-2.csv")
mdata <- read.csv(url, stringsAsFactors = FALSE)

crude_rate <- 500000

nat_cause <- aggregate(cbind(Deaths, Population) ~ ICD.Chapter + Year, mdata, FUN = sum)
nat_cause$NatAvge <- round(nat_cause$Deaths / nat_cause$Population * crude_rate, 4)

server <- function(input, output, session) {
  sub_mdata <- reactive({subset(
    mdata, ICD.Chapter == input$causes & State == input$state_name,
    select = c(Year, Crude.Rate, ICD.Chapter)
  )})

  new_df <- reactive({
    df <- sub_mdata()
    colnames(df) <- c("Year", "Rate_State", "ICD.Chapter")
    merge(df, nat_cause, by=c("Year", "ICD.Chapter")) %>%
      dplyr::mutate(state_diff = lag(Rate_State) - Rate_State) %>%
      dplyr::mutate(nat_diff = lag(NatAvge) - NatAvge) %>%
      dplyr::mutate(st_nat = (state_diff - nat_diff))
  })

  output$causev <- renderPlot({
    ggplot(data=new_df(), aes(x=Year, y=st_nat)) + geom_line()
  })
}

ui <- fluidPage(

  #Application title
  titlePanel("Mortality Improvement by State"),

  #Dropdown state and cause
  sidebarLayout(
    sidebarPanel(
      selectInput("state_name", "State:", choices = unique(mdata$State)),
      radioButtons("causes", "Select disease - cause of Death:",
                   unique(mdata$ICD.Chapter))
    ),
    # Show a plot of the generated distribution
    mainPanel(plotOutput("causev"))
  )
)

shinyApp(ui, server)
Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43