Error in Running R script in Shiny

shiny

#1

I am trying to make it so that when I run this app, upon initialization the app would call another script so that I have the dataframes available to run the app on. but every time I try I get the error “ERROR: Cannot open the connection” here is the script:

# # server code to get the RAM in Shiny
## the following is an R script I have already made that I need to run when the app gets initialized
## but never run again.  R script in titled "Ram in R.R"
Item <- read.delim("../R&D1/Risk Assessment Model/by_itm9.txt",header = TRUE, sep="|", quote = "", dec = ".",
                  colClasses = c(Root  ="character", DS="character"))
Policy <-read.delim("../R&D1/Risk Assessment Model/by_pol9.txt",header = TRUE,sep="|",quote="",dec = ".",
                    colClasses = c(Root  ="character", DS="character"))
## make the two dataframes match in column order and headers
NewCol1 <- c("Sec", "ItmNo","ItmType")
Policy[NewCol1] <- "All"
Policy <- subset(Policy, select = c(1,40:42,2:34,36:37,35,38:39))
colnames(Policy)[colnames(Policy)=="IndPrem"] <- "CorrPrem"
colnames(Policy)[colnames(Policy)=="Terr"] <- "Territory"
colnames(Item)[colnames(Item)=="CombISCorr"] <- "ISCorr"
colnames(Item)[colnames(Item)=="Prem"] <- "ActPrem"
colnames(Item)[colnames(Item)=="Corr"] <- "CorrFac"
## end of R script

#source("RAM in R.R", local = TRUE)
library(DT)
library(shiny)
#define UI dataset viewer application
ui<- fluidPage(
  shinyUI(verticalLayout(
    #Application title
    headerPanel("R.A.M. Results"),
    #Sidebar with controls to select a dataset and specify root numbers.
    sidebarPanel(
      fluidRow(
        textInput(inputId = "root",label = NULL ,placeholder = "Enter Root number here"),
        helpText(
          tags$em("Note:  The root number must include all 6 digits e.g. 000107")
        )
      ),
      fluidRow( # made check boxes to allow users to view data in multiple ways.
        column(
          8, checkboxGroupInput(inputId = "mods",label = "Options", choices = c("All Policy Items","Expand Table"), 
                                selected = "All Policy Items", inline = FALSE)
        ),
        column(
          4,offset = 8, actionButton(inputId = "go", label = "Update")
        )
      )
    ),
    mainPanel(
      div(DT::dataTableOutput("RAMResults"),
          style = "font-size:70%; width:50%")
    )
  ))
)
server <- function(input,output) {
  #the eventReactive code is the delayed reaction.
  root1 <- eventReactive(input$go, {input$root})
  PolSummary <- reactive({
    if ("Expand Table" %in% input$mods) {  
      policyDetails <- reactive({
        Policy[Policy$Root == root1(),c(2:9,12:14,17,19,21:23,25:26,29,32,34,36:42)]
      }) # IF we want DS number (i.e. 1,2,3) add in column 18
      ItemDetails <- reactive({
        Item[Item$Root == root1(), c(2:9,25:26,35,46,54,62:63,72,74,83,98,109,120,126:132)]
      })
    } else if (!"Expand Table" %in% input$mods) {
      policyDetails <- reactive({
        Policy[Policy$Root == root1(),c(2:9,12:14,21,32,37:40)]
      }) # IF we want DS number (i.e. 1,2,3) add in column 18
      ItemDetails <- reactive({
        Item[Item$Root == root1(), c(2:9,25:26,35,62,109,127:130)]
      })
      formattable(policyDetails(),list(
          ISCorr = color_bar('red')
        )
      )
    }
    # IF we want DS number (i.e. 1,2,3) add in column 47
    #the if else statment allows to look at just the policy summary data or look at everything, 
    #if we remove this keep the rbind line "THIS ONE" only 
    #(rbind (policyDetails(),ItemDetails(),deparse.level = 1)
    if ("All Policy Items" %in% input$mods) {
      rbind(policyDetails(),ItemDetails(),deparse.level = 1) #THIS ONE
    } else if (!"All Policy Items" %in% input$mods) {
      rbind(policyDetails(),deparse.level = 1)    
    }
  })
  
  output$RAMResults  <- DT::renderDataTable({
    if("Expand Table" %in% input$mods) {
      DT::datatable(PolSummary(), rownames = FALSE, extensions = c('Buttons','FixedHeader'), options = list( 
        lengthMenu = c(10,25,50), pageLength = 50, class = 'cell-border', fixedHeader = TRUE, dom = 'Bfrtip', buttons = list(list(extend = 'colvis', columns = c(7:25)))
        ) 
      ) %>%formatStyle(c('ISCorr','LoyCorr','PmtCorr','DSCorr','ItmAgeCorr','TerrCorr','IRPMCorr','InsAgeCorr','LRCorr','PCCorr','PolSizeCorr','CorrFac'),
          color = styleInterval(c(.95,.99999,1.0,1.05),c('white','black','black','black','white')), 
          backgroundColor = styleInterval(c(.85,.95,.99999,1.0,1.05,1.15),c('darkgreen','green','lightgreen','white','pink','red','darkred')), fontWeight = 'bold' 
        )
    } else if (!"Expand Table" %in% input$mods) {
      DT::datatable(PolSummary(), rownames = FALSE, extensions = c('Buttons','FixedHeader'), options = list( 
        lengthMenu = c(10,25,50), pageLength = 50, class = 'cell-border', fixedHeader = TRUE, dom = 'Bfrtip', buttons = list(list(extend = 'colvis', columns = c(7:16)))
        ) 
      ) %>%formatStyle(c('ISCorr','LoyCorr','ItmAgeCorr','LRCorr','CorrFac'),color = styleInterval(c(.95,.99999,1.0,1.05),
          c('white','black','black','black','white')), backgroundColor = styleInterval(c(.85,.95,.99999,1.0,1.05,1.15),
          c('darkgreen','green','lightgreen','white','pink','red','darkred')), fontWeight = 'bold' 
        )
    }  
  }) 
}
#run the ui and server in the same tab and be able to save it with unique identifying names.
shinyApp(ui = ui, server = server)

#2

You can rename ‘Ram in R.R’ to global.R and put global.R in the same directory as app.R. Shiny will source global.R automatically (see 14.8 in https://deanattali.com/blog/building-shiny-apps-tutorial/#14-more-shiny-features-to-check-out).


#3

so i’ve renamed the script ‘global.R’ and it is saved in the same place as my app (titled ‘Ram Shiny’), if the source(“global.R”, local = FALSE) in before the ui code or in the ui code I still get the same error…

#tried it here too....
library(DT)
library(shiny)
#define UI dataset viewer application
ui<- fluidPage(
  source("global.R", local = FALSE),
  shinyUI(verticalLayout(
    #Application title
    headerPanel("R.A.M. Results"),
    ... (code continues)

#4

You don’t need to explicitly source global.R. Also, I usually just put the data in the app directory. Maybe your path names are the problem. This might help: https://stackoverflow.com/questions/12048436/r-sourcing-files-using-a-relative-path?


#5

I’ve moved the data to the same directory, I have changed the name of the script to app.R, I have the global.R script pulling the data from that director, if I don’t source global.R directly the app pulls up but doesn’t work as it has no data behind it, if I source it directly it gives the error again…


#6

From http://shiny.rstudio.com/articles/scoping.html

Global objects

Objects defined in global.R are similar to those defined in app.R outside of the server function definition, with one important difference: they are also visible to the code in the ui object. This is because they are loaded into the global environment of the R session; all R code in a Shiny app is run in the global environment or a child of it.

Not sure why your app isn’t displaying the data correctly.


#7

when I moved everything over into the same directory I ddidn’t make the necessary corrections. I figured out that bad code and now it all works thanks for the help!