Error Running R-Shiny App: "if (inline) { : the condition has length > 1"

Hi,

I'm writing a Shiny App and it's been running totally fine , but now when I try to run it I'm getting an error that says:

"Error in if (inline) { : the condition has length > 1"

The underlying code renders totally fine in markdown, so I think it's something in the UI or server code that's generating the error.

In other topic posts, it looks like this error may be caused by parentheses being formatted incorrectly ; however, I've checked all brackets and parentheses pretty carefully and still can't find it. It's driving me nuts!

Can anyone see what's causing this?


## Load Necessary Packages ##

library(shiny)
library(rgdal)
library(ggmap)
library(survey)
library(leaflet)
library(rsconnect)
library(stargazer)
library(tidyverse)
library(shinythemes)

## Prep Data ##

schools <- read.csv("Philly_schools.csv")

colnames(schools)

philhs <- schools %>% 
  filter(SCHOOL_LEVEL_NAME == "HIGH SCHOOL") %>%
  select(-SCHOOL_NAME_2, -ZIP_PLUS_4, -CITY, -STATE_CD, -PHONE_NUMBER, -SCH_START_GRADE, -SCH_TERM_GRADE, 
         -HPADDR, -One_suspension, -Two_suspensions, -Three_suspensions, -Three_plus_suspensions) %>%
  mutate(Suspensions_per_student = Total_suspensions / Enrollment,
         Enrollment = (Enrollment / 100),
         Average_salary = (Average_salary / 1000)) %>%
  rename(Student_attendance = Attendance,
         Students_new = New_student,
         Students_withdraw = Withdrawals,
         Black = African_American,
         School_name = SCHOOL_NAME_1,
         Special_ed = Special_education,
         Gifted_ed = Gifted_education,
         Esl_ed = English_second_language)

philhs <- philhs %>% 
  mutate_if(is.numeric, round, 2)

philhs$Other <- philhs$Other + philhs$Pacific_Islander

philhs$Full_address <- paste(philhs$ADDRESS, philhs$SCHOOL_ZIP)

philhs <- philhs %>% 
  select(-Pacific_Islander, -ADDRESS, -SCHOOL_ZIP, -SCHOOL_LEVEL_NAME, -Total_suspensions)

names(philhs) <- tolower(names(philhs))

philhs$school_name <- str_to_title(philhs$school_name)
philhs$full_address <- str_to_title(philhs$full_address)

philhs <- philhs %>%
  select(school_code, school_name, full_address, enrollment, student_attendance, students_new, 
         students_withdraw, asian, black, latino, white, other, gifted_ed, special_ed, esl_ed, 
         low_income_family, assaults, drugs, morals, thefts, weapons, suspensions_per_student, 
         teacher_attendance, average_salary)

philhs$latitude <- NA
philhs$longitude <- NA

# Geocode Addresses

register_google(key = "AIzaSyCvczezGYImw6stEa21JufnD0rm8Cr28sg")

datageo <- geocode(as.character(philhs$full_address), source = "google")

philhs$latitude <- datageo$lat
philhs$longitude <- datageo$lon

# Remove Original Data

rm(schools)

# Calculate the City Average for Variables of Interest

add_row(philhs)

philhs[41, 1] <- NA
philhs[41, 2] <- "City Average"
philhs[41, 3] <- NA
philhs[41, 4] <- mean(philhs$enrollment[1:40])
philhs[41, 5] <- mean(philhs$student_attendance[1:40])
philhs[41, 6] <- mean(philhs$students_new[1:40])
philhs[41, 7] <- mean(philhs$students_withdraw[1:40])
philhs[41, 8] <- mean(philhs$asian[1:40])
philhs[41, 9] <- mean(philhs$black[1:40])
philhs[41, 10] <- mean(philhs$latino[1:40])
philhs[41, 11] <- mean(philhs$white[1:40])
philhs[41, 12] <- mean(philhs$other[1:40])
philhs[41, 13] <- mean(philhs$gifted_ed[1:40])
philhs[41, 14] <- mean(philhs$special_ed[1:40])
philhs[41, 15] <- mean(philhs$esl_ed[1:40])
philhs[41, 16] <- mean(philhs$low_income_family[1:40])
philhs[41, 17] <- mean(philhs$assaults[1:40])
philhs[41, 18] <- mean(philhs$drugs[1:40])
philhs[41, 19] <- mean(philhs$morals[1:40])
philhs[41, 20] <- mean(philhs$thefts[1:40])
philhs[41, 21] <- mean(philhs$weapons[1:40])
philhs[41, 22] <- mean(philhs$suspensions_per_student[1:40])
philhs[41, 23] <- mean(philhs$teacher_attendance[1:40])
philhs[41, 24] <- mean(philhs$average_salary[1:40])
philhs[41, 25] <- NA
philhs[41, 26] <- NA

# Select Variables for School Comparison

philhs_small <- philhs %>% 
  select("school_name", "enrollment", "student_attendance", "students_new", "students_withdraw",
         "gifted_ed","special_ed", "special_ed", "esl_ed", "low_income_family", "assaults", "drugs",
         "morals", "thefts", "weapons", "suspensions_per_student", "teacher_attendance", "average_salary")

# Format Data for School Comparison Facet Wrap

philhs_long <- philhs_small %>% 
  pivot_longer(c("enrollment":"average_salary"),
               names_to = "Variable",
               values_to = "Value")

# Remove Unformatted Comparison data

rm(philhs_small) 

# Create Survey Design for Regression

design <- svydesign(id = ~0, data = philhs, na.rm = TRUE)

# Select Variables for Diversity Analysis 

philhs_div <- philhs %>% 
  select("school_name", "asian", "black", "latino", "white", "other")

philhs_div <- philhs_div %>% 
  pivot_longer(c("asian":"other"),
               names_to = "Race",
               values_to = "Value")

#########
## UI ##
#########

ui <- shinyUI(fluidPage(theme = shinytheme("superhero"),
                        
                        navbarPage("Philly High School Explorer", # navigation bar
                                   tabPanel("Home", # home page
                                            tags$head(),
                                            headerPanel("Welcome to the Philly High School Explorer!"),
                                            br(), 
                                            br(),
                                            br(),
                                            h2("How to Use This App"),
                                            br(),
                                            h4("This app is designed to help you explore, analyze, 
                                               and compare Philadelphia high schools; each page provides you 
                                               with a useful tool."),
                                            br(),
                                            h4(tags$ul(
                                              tags$li(strong("Philly High Schools Map:"), "Explore schools near you, 
                                                      or search around the city! Click on school markers to see key 
                                                      statistics, including enrollment, student and teacher attendance, 
                                                      gifted program and special education participation, and more 
                                                      concerning statistics such as annual suspensions per student and
                                                      assaults per 100 students; information to help you find the right 
                                                      school for your family."), # bullet point
                                              br(),
                                              tags$li(strong("Predict School Attendance:"), "Explore what factors 
                                                      predict student attendance! Select variables, including percent 
                                                      of students from low-income families, annual suspensions per student,
                                                      assaults per 100 students, average number of student withdrawals
                                                      per year, average teacher salary, and gifted program and special
                                                      education participation, and see how much of an effect these variables
                                                      have on average student attendance."), # bullet point
                                              br(),
                                              tags$li(strong("Compare Schools:"), "Once you have a few schools in mind, 
                                                      visit this page to directly compare schools with one another and 
                                                      with city averages on a host of dimensions."), # bullet point
                                              br(),
                                              tags$li(strong("View School Diversity:"), "View student body diversity adding richness to the student 
                                              experience beyond academics. ") # bullet point
                                            )  # bullet list
                                            ), # sub heading text (h4)
                                            br(),
                                            br(),
                                            imageOutput("hs"),
                                            br(),
                                            br(),
                                   ), # tab panel (home page)
                                   
                                   tabPanel("Philly High Schools Map", # map page
                                            tags$head(),
                                            headerPanel("Philly High Schools Map"),
                                            br(),
                                            h2(""),
                                            br(),
                                            br(),
                                            leafletOutput("map", width = "800px", height = "800px"),
                                            br(),
                                   ), # tab panel (map page)
                                   
                                   tabPanel("Predict School Attendance", # prediction page
                                            tags$head(),
                                            headerPanel("Predict School Attendance"),
                                            
                                            # Create Side Bar for Selecting Input Variables
                                            sidebarLayout(
                                              position = "right",
                                              sidebarPanel(
                                                h2("Customize Your Model"),
                                                br(),
                                                checkboxGroupInput("iv1",
                                                                   label = "Select any of the input (independent) variables below to 
                                                                   calculate your prediction model. You can change your selection at any time.",
                                          br(),
                                          c("Average Teacher Salary in 1000s" = "average_salary",
                                            "Average Percent Teacher Attendance" = "teacher_attendance",
                                            "Percent of Students Receiving Gifted Education" = "gifted_ed",
                                            "Percent of Students Receiving Special Education" = "special_ed",
                                            "Percent of Students Receiving ESL Education" = "esl_ed",
                                            "Percent of Students from a Low-Income Family" = "low_income_family",
                                            "Assaults Per 100 Students" = "assaults",
                                            "Average Annual Suspensions Per Student" = "suspensions_per_student",
                                            "Average Annual Student Withdrawals"= "students_withdraw"), # c
                                          selected = "average_salary"
                                                ) # checkbox Group Input
                                              ), # side bar panel
                                          
                                          mainPanel(br(),
                                                    # Create Tab Panel for Regression Table
                                                    tabsetPanel(
                                                      type = "tabs",
                                                      
                                                      # Panel Shows Regression Table
                                                      tabPanel(
                                                        "Regression Table",
                                                        h3("Table of Regression Coefficients"),
                                                        HTML('</br>'),
                                                        tableOutput("regTab"),
                                                        HTML('</br>'),
                                                        helpText("The table displays the coefficients of your model. Larger coefficient numbers
                                                             indicate that the variable has a greater effect on the outcome (dependent)
                                                             student attendance variable. A positive coefficient indicates that an increase
                                                             in the variable increases student attendance (e.g., a higher average teacher
                                                             salary indicates likelihood of higher student attendance), while a negative
                                                             coefficient indicates that an increase in the variable decreases student
                                                             attendance (e.g., a higher number of assaults per 100 students indicates
                                                             likelihood of lower student attendance). Whether the effect of a given variable
                                                             is statistically significant is indicated by “*”, “**”, or “***” next to the
                                                             coefficient, and a P-Value less than 0.05. A greater number of stars and a 
                                                             P-Value closer to 0 indicate a higher level of statistical significance.")
                                                      ) # tab panel
                                                    ), # tab set panel
                                          ) # main panel
                                            ) # side bar layout
                                   ), # tab panel (prediction page)
                                   
                                   tabPanel("Compare Schools",
                                            tags$head(),
                                            headerPanel("Compare Schools"),
                                            
                                            # Create Side Bar for Selecting Input Variables 
                                            sidebarLayout(
                                              position = "left",
                                              sidebarPanel(br(),
                                                           selectizeInput("sch1", "School of Interest:",
                                                                          choices = sort(unique(philhs_long$school_name)), 
                                                                          selected = "Abraham Lincoln High" ),
                                                           selectizeInput("sch2", "Benchmark School:", 
                                                                          choices = sort(unique(philhs_long$school_name)), 
                                                                          selected = "City Average")
                                              ), #side bar panel
                                              
                                              # Create panel for displaying rendered ggplot
                                              mainPanel(br(),
                                                        plotOutput("plot"),
                                                        helpText(strong("Assaults:"),"Assaults per 100 students", br(),
                                                                 strong("Student Attendance:"),"Average percent student attendance", br(),
                                                                 strong("Average Salary:"),"Average teacher salary in 1000s", br(),
                                                                 strong("Drugs:"),"Drug infractions per 100 students", br(),
                                                                 strong("ESL Education:"),"Average percent student attendance", br(),
                                                                 strong("Enrollment:"),"Average enrollment in 100s", br(),
                                                                 strong("Gifted Education:"),"Percent of students receiving gifted education", br(),
                                                                 strong("Low Income Families:"),"Percent of students from a low income family", br(),
                                                                 strong("Students New:"),"Average number of new students per year", br(),
                                                                 strong("Special Education:"),"Percent of students receiving special education", br(),
                                                                 strong("Suspensions Per Student:"),"Average annual suspensions per student", br(),
                                                                 strong("Teacher Attendance:"),"Average percent teacher attendance", br(),
                                                                 strong("Thefts:"),"Thefts per 100 students", br(),
                                                                 strong("Weapons:"),"Weapons infractions per 100 students", br(),
                                                                 strong("Withdrawals:"),"Average number of students who withdraw from the school per year", br(),
                                                        ) # help text
                                              ) # main panel
                                            ) # side bar layout
                                   ), # tab panel (comparison page)
                        ) # navbar
) # fluid page
) # shiny ui

############
## Server ##
############

# Define server logic required to draw a histogram
server <- function(input, output) {
  
  ## Add a Home Page Photo ##
  output$hs <- renderImage({
    # generate bins based on input$bins from ui.R
    list(src = "www/hs.jpg",
         width = "75%",
         height = "100%",
         style ="display: block; margin-left: auto; margin-right: auto")
  }, deleteFile = F)
  
  ## Create Map of Philly High Schools ##
  map <- leaflet() %>%
    addTiles() %>%
    addMarkers(~longitude, ~latitude, data = philhs, 
               popup = paste("<strong>School:</strong>", philhs$school_name,"<br>",
                             "<strong>Address:</strong>", philhs$full_address,"<br>",
                             "<strong>Average Enrollment in 100s:</strong>", philhs$enrollment,"<br>",
                             "<strong>Average Student Attendance:</strong>", philhs$student_attendance,"%","<br>",
                             "<strong>Average Teacher Attendance:</strong>", philhs$teacher_attendance,"%","<br>",
                             "<strong>Students Receiving Gifted Education:</strong>", philhs$gifted_ed,"%","<br>",
                             "<strong>Students Receiving Special Education:</strong>", philhs$special_ed,"%","<br>",
                             "<strong>Students Receiving ESL Services:</strong>", philhs$esl_ed,"%","<br>",
                             "<strong>Average Annual Suspensions Per Student:</strong>", philhs$suspensions_per_student,"<br>",
                             "<strong>Assaults Per 100 Students:</strong>", philhs$assaults,"<br>"))
  
  # Create Map Output
  
  output$map <- renderLeaflet(map)
  
  ## Create Regression Model to Predict Student Attendance ##
  
  # Create Reactive Regression Formula Using Inputs from Check List as Variables to Predict Student Attendance
  
  RegFormula <- reactive({
    as.formula(paste("student_attendance", " ~ ", paste(input$iv1, collapse = "+")))
    
  })
  
  # Output Reactive Regression
  
  model <- reactive({
    svyglm(regFormula(), design)
    
  })
  
  # Create Regression Table Output
  
  output$regTab <- renderText({
    stargazer(model(), type = "html", dep.var.labels = "Student Attendance Prediction", omit.stat = c("ll", "aic"))
    
  })
  
  ## Create Plots to Compare Schools Based on Variables of Interest ##
  
  # Create Reactive Comparison Using Inputs from Dropdowns
  
  twoschl <- reactive({
    x <- philhs_long %>%
      filter(school_name == input$sch1 | school_name == input$sch2)
    x$school_name <- factor(x$school_name, levels = c(input$sch1, input$sch2))
    x
    
  })
  
  # Create Comparison Plots Output
  
  output$plot <- renderPlot({
    ggplot(data = twoschl, aes(x = school_name, y = Value, fill = school_name)) +
      geom_bar(stat = "identity") + 
      facet_wrap( ~ Variable) + 
      scale_fill_manual(values = c("#ffc404", "#303c54")) +
      ylim(0,100) + 
      theme(axis.text.x = element_blank()) + 
      xlab("Schools") +
      guides(fill = guide_legend("Schools"))
    
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

It's difficult to troubleshoot without the data. Are you able to share the following (or a subset)?

schools <- read.csv("Philly_schools.csv")

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.