Integrating R code with Shiny app


#21

You need to use backticks (on my keyboard it is in the top left above the tab button and below esc) not single quotes to create the code block.

There should be a preview panel on the right when you type your posts. Your code should look like this (referring to the post format, and not your coding style):

# test block of code 
# 
data %>% foo() %>% print()

#22

[quote=“giuseppa.cefalu, post:20, topic:3539”]
I am getting this error

“cannot coerce class “c(“shiny.render.function”, “function”)” to a data.frame”

when I run the code:

’’’

output$tb <- renderUI({

if(is.null(data())){

return()

}else{

tabsetPanel(tabPanel(“Data”, tableOutput(“table”)))
}

})

’’’

The main panel contains


uiOutput(“tb”)

Do you know where this comes from, usually?

data is referring to this:


data &lt;- reactive({

output$inputFile &lt;- renderTable({

fileToRead = input$inputFile

if(is.null(fileToRead)){

return()

}

read.table(fileToRead$datapath, sep = input$sep, header = input$header, stringsAsFactors = input$stringsAsfactors)

})

})

I fixed. Does it work now?


#23

I am sending all the core:

library(shiny)

ui <- fluidPage(
  
  tags$head(
    tags$style(HTML("
                    @import url('//fonts.googleapis.com/css?family='Helvetica', 'Arial', sans-serif:400,700');
                    "))
    ),
  fluidRow(
    column(width = 3, offset = 1),
    headerPanel(
      h1("glycoPipe - Identification and Analysis Pipeline R Package", 
         style = "font-family: 'Lobster', 'cursive';
         font-weight: 500; line-height: 1.1; 
         color: #394779;"))
      ),
  

  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(width = 3, offset = 0,
               img(src="logo.jpeg", height = 50, width = 200, align = "middle"))
      ),
      fluidRow(
        column(width = 3, offset = 0,div(style = "height:25px;background-color: #99CCFF", strong("Urology"))
        )
      ),
     
     # "")
      #fileInput("file", "upload the file"),
      #h5("Max file size to upload is 5 MB")
    fluidRow(
    column(width = 10,
         
           selectInput("value", label = h4("Do you have a parameter file ready to use, Y/N?"), 
                       choices =c("", "Y" , "N"), selected = NULL))
    ),
    conditionalPanel(
    condition = "input.value == 'Y'",
    helpText(h4("Select your params file")),
    fluidRow(
      column(width = 10,fileInput("file", "upload the file" ),
             helpText("Default max file size 5 MB"),
             tags$hr(),
             h5(helpText("select the parameters below")),
             checkboxInput(inputId = "Header","Header?", value = FALSE),
             br(),
             radioButtons(inputId = "sep", label = "separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t", Space = " "))
      )
      
    )
    )
    
  
    ),
    

    
    mainPanel(
      #textOutput("value"),
      uiOutput("tb")
      #tableOutput("inputFile")
    )

  )
)
    


 server <- function(input, output){
   
 # output$value <- renderText({
    # paste("You chose", input$value)
  # })
  data <- reactive({
  output$inputFile <- renderTable({
    fileToRead = input$inputFile
    if(is.null(fileToRead)){
      return()
    }
    
    read.table(fileToRead$datapath, sep = input$sep, header = input$header, stringsAsFactors = input$stringsAsfactors)
  })
 })
  
  
  output$table <- renderDataTable({
    if(is.null(data())){
      return()
    }
    data()
  })
   
  output$tb <- renderUI({
    if(is.null(data())){
      return()
    }else{
   
      tabsetPanel(tabPanel("Data", tableOutput("datatable")))
    }
  })
 }
 
 shinyApp(ui = ui, server = server)

I made a change in one of the functions. Instead of using “renderTable” I used “renderDataTable”. Th error is gone, but when I click on the tab, the data does not get displayed


#24

Does it have to do with the fact that I am trying to upload a .tsv file?


#25

I think you issue is with your data reactive. You are trying to create an output within the reactive() function which is a discouraged practice by @jcheng. Try this in that reactive function and see if it works:

data <- reactive({
  fileToRead = input$inputFile
  if(is.null(fileToRead)){
    return()
  }
    
  read.table(fileToRead$datapath, sep = input$sep, header = input$header, stringsAsFactors = input$stringsAsfactors)
 })

#26

In addition, you use the outputId of table when creating the datatable and then pass the outputId of datatable to your renderDataTable() function. If these do not match, nothing will be displayed


#27

I have made those changes and now I get:
“Listening on http://127.0.0.1:3763
Warning in if (!is.na(attribValue)) { :
the condition has length > 1 and only the first element will be used
Warning in charToRaw(enc2utf8(text)) :
argument should be a character vector of length 1
all but the first element will be ignored” and the tab does not show up in the main panel


#28

I solved that problem, but still I cannot get the data file to display in main panel. Would you take a look at the code please?


ui <- fluidPage(
  
  tags$head(
    tags$style(HTML("
                    @import url('//fonts.googleapis.com/css?family='Helvetica', 'Arial', sans-serif:400,700');
                    "))
    ),
  fluidRow(
    column(width = 3, offset = 1),
    headerPanel(
      h1("glycoPipe - Identification and Analysis Pipeline R Package", 
         style = "font-family: 'Lobster', 'cursive';
         font-weight: 500; line-height: 1.1; 
         color: #394779;"))
      ),
  
  
  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(width = 3, offset = 0,
               img(src="logo.jpeg", height = 50, width = 200, align = "middle"))
      ),
      fluidRow(
        column(width = 3, offset = 0,div(style = "height:25px;background-color: #99CCFF", strong("Urology"))
        )
      ),
      
      # "")
      #fileInput("file", "upload the file"),
      #h5("Max file size to upload is 5 MB")
      fluidRow(
        column(width = 10,
               
               selectInput("value", label = h4("Do you have a parameter file ready to use, Y/N?"), 
                           choices =c("", "Y" , "N"), selected = NULL))
      ),
      conditionalPanel(
        condition = "input.value == 'Y'",
        helpText(h4("Select your params file")),
        fluidRow(
          column(width = 10,fileInput("file", "upload the file" ),
                 helpText("Default max file size 5 MB"),
                 tags$hr(),
                 h5(helpText("select the parameters below")),
                 checkboxInput(inputId = "Header","Header?", value = FALSE),
                 br(),
                 radioButtons(inputId = "sep", label = "separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t", Space = " "))
          )
          
        )
      )
      
      
    ),
    
    
    
    mainPanel(
      #textOutput("value"),
      tableOutput("fileToRead")
      
    )
    
  )
)



server <- function(input, output){
  
  # output$value <- renderText({
  # paste("You chose", input$value)
  # })
  output$input_file <- renderTable({
    fileToRead = input$file
    if(is.null("FileToRead")){
      return()
    }
    
    read.table(fileToRead$datapath, sep = input$sep, header = input$header, stringsAsFactors = input$stringsAsFactors)
  })
}

shinyApp(ui = ui, server = server)

#29

I think this is the correct code based on what I have read. However, I keep getting the same error: file must be a character string or connection. Any hints?

library(shiny)

ui <- fluidPage(
  
  tags$head(
    tags$style(HTML("
                    @import url('//fonts.googleapis.com/css?family='Helvetica', 'Arial', sans-serif:400,700');
                    "))
    ),
  fluidRow(
    column(width = 3, offset = 1),
    headerPanel(
      h1("glycoPipe - Identification and Analysis Pipeline R Package", 
         style = "font-family: 'Lobster', 'cursive';
         font-weight: 500; line-height: 1.1; 
         color: #394779;"))
      ),
  
  
  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(width = 3, offset = 0,
               img(src="logo.jpeg", height = 50, width = 200, align = "middle"))
      ),
      fluidRow(
        column(width = 3, offset = 0,div(style = "height:25px;background-color: #99CCFF", strong("Urology"))
        )
      ),
      
      # "")
      #fileInput("file", "upload the file"),
      #h5("Max file size to upload is 5 MB")
      fluidRow(
        column(width = 10,
               
               selectInput("value", label = h4("Do you have a parameter file ready to use, Y/N?"), 
                           choices =c("", "Y" , "N"), selected = NULL))
      ),
      conditionalPanel(
        condition = "input.value == 'Y'",
        helpText(h4("Select your params file")),
        fluidRow(
          column(width = 10,fileInput("file", "upload the file" ),
                 helpText("Default max file size 5 MB"),
                 tags$hr(),
                 h5(helpText("select the parameters below")),
                 checkboxInput(inputId = "Header","Header?", value = FALSE),
                 br(),
                 radioButtons(inputId = "sep", label = "separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t", Space = " "))
          )
          
        )
      )
      
      
    ),
    
    
    
    mainPanel(
      #textOutput("value"),
      tableOutput("contents")
      
    )
    
  )
)



server <- function(input, output){
  
  # output$value <- renderText({
  # paste("You chose", input$value)
  # })
  output$contents <- renderTable({
    inFile = input$file
    if(is.null("inFile")){
      return()
    }
    
    read.table(file = inFile$datapath, sep = input$sep, header = input$header, stringsAsFactors = input$stringsAsFactors)
  })
}

shinyApp(ui = ui, server = server)


#30

It seems that the file is not structured like a regular csv or text fie and therefore read.table () does not work. Instead I am using readLines.

When I upload a file using File input, I get a progress bar that completes and get the message upload is complete. Where is the file uploaded? how can I find the uploaded file?


#31

Thought someone could use this code.

The problem is solved using req(inFile) before the statement
read.delim(inFile$datapath, sep = '\t')

req(inFile)
read.delim(inFile$datapath, sep = '\t')

#32

I have used source("subfolder/utilities.R)
utilities.R contains a function that is called by a helper function created outside the UI and server in the app.R file

if I define a variable in the helper function such as group_type=1

helperFunction <- function(){
group_type = 1
list(group_type = group_type)
}

I can extract the value in the server function using the following:

server <- function(input, output){
observeEvent(input$btn,{
    result <- function()
    value = result$group_type
    output$textbox <- renderText({
      paste("Runnin glycoPipe in ", value)
    })
    hide("btn")
  })

}

and everything runs fine -when the user clicks the start button the function() runs and I can extract the value of the variable defined in the helper function.

Now I am facing a similar issue: with 2 questions?

  1. How can I extract the name of the file uploaded by the user and store it in variable that can be used both by the server function, the helper function and the UI?

  2. the helper function() called from the server function calls another function in source(utilities.R). The function name called from the server is pass <- helperFunction() and the name of the function in the utilities.R script is function2. In this case, I would like to get the value of variable pass returned by function2 to helperFunction().

  3. how can extract it so that it can be used by the helper function the server function and the UI?

This would be more or less the idea for the code:

helperFunction <- function(filename){
pass <- function2()

list(pass = pass)
}

the function called by the helper function which is in source(utilities.R) would be

function2(filename){
pass.

}

Then in the server I would do something like

server <- function(input, output){
observeEvent(input$something,{
    result <- function()
    #how do I access the value returned by the function called by the helper function when the #server calls the helper function?
    value = result$pass
    output$textbox <- renderText({
      paste("The response was", value)
    })
}

to summarize:

This is the helperFunction call in the app.R file:

helperFunction(){
pass <- function2(filename)
}

This is the function n utilities.R including source(utilities.R) in app.R

function2(filename){ 
  # some processing ..........
  pass
}

Thanks


#33

I made a correction to my previous post. I forgot to get and pass filename in the server function call. I do not get the return value of the function call (pass) and the gui closes when I run the start app button. I do not have more ideas so far.


#34

Everything works fine when I do not use sourcing: Please see below. But if checkParams(fileName) is in defined in another script and I source the script, the program fails with error in system.file: ‘package’ must be of length 1. What seems to be wrong?
ui <- fluidPage()

glycoPipe <- function(PARAMSfullFile=NULL){
list(pass = pass)
     pass<- checkParams(PARAMSfullFile)
    if (!pass) return()

}

checkParams <- function(PARAMSfullFile = NULL){
  pass = TRUE
}
server <- function(input, output, session){
  
  observeEvent(input$value,{
  result <- glycoPipe(checkParams(input$file$name))
  value = result$pass
  output$box <- renderText({
   paste("Your result is", value)
   })
    
 })

}

#35

Doing progress here. I found that is the utilities.R file is in the same directory as the app.R file, everything works fine. However, if I save the utilities file in a subdirectory of the directory where the app.R script is it does not work. For example: source(“utilities.R”) as opposed to source("/folder/utilities.R"). Any idea why this happens?


#36

My app is in /home/user/Development/testSource and my utilities.R is in /home/user/Development/testSource/utilityFolder/utilities.R. My working direectory -getwd()- is /home/user/testSource. When i save the utility file in testSource where the app is stored, source(“utilities.R”) works fine, but if I save the utilities.R file in utilityFolder, source(“home/user/testSource/utilityFolder/utilities.R”) does not work. Neither does source(“testSource/utilityFolder/utilities.R”)


#37

It finally worked using: source("~/Development/testSource/UtilityFoler/utilities.R",chdir = TRUE)


#38

To source() the file from a sub folder within the apps working directory you need to do this:

source("utilityFolder/utilities.R")

You should avoid absolute file paths as they make reproducing your code much harder for other users (and yourself if you use a different computer or modify your folder structure in the future)


#39

Thank you for your response.


#40

I do not seem to get this right. the return value of pass is always TRUE
glycoPipe <- function(PARAMSfullFile){

pass <- checkParams(PARAMSfullFile)
}

checkParams <- function(PARAMSfullFile){

pass = FALSE
}

observeEvent(input$value,{
if(input$value == ‘Y’){
result <- glycoPipe(input$file$name)
returnValue = result$pass
if(returnValue == TRUE){
output$box <- renderText({
paste(“Your result is”, returnValue)
})
}
}
})