How to use external functions within the server using Shiny?

Asked

Viewed 118 times

2

I am creating a graphical interface for an algorithm I developed in R language. The algorithm has several scripts with functions that talk to each other, and after started, it takes hours to complete. I am using the Shiny package with its inputs to collect the parameters of the algorithm, and so put it to run. However, I’m not succeeding. The algorithm has no graphical outputs, only writes files on the machine itself.

The code follows, where algorithm is the code to be called, and algoritmo.R is where all scripts with functions are located.


ui <- ... (
  ...
  tabPanel ("Resultados",
    textOutput ("resultados")
  )
)

server <- function (input, output) {
  ...
  output$resultados <- eventReactive ({
    if (input$iniciar)
      isolate (algoritmo (input))
  })
}

source ('algoritmo.R')

1 answer

1


Just put source() at the beginning of the code. Be histogramaVermelho.R a file with a function that makes a red histogram:

histogramaVermelho <- function(x, breaks = 10){
  hist(x, breaks, col="red")
}

Just save this code to the file histogramaVermelho.R and build the following app:

source("histogramaVermelho.R")

library(shiny)

# ui

ui <- fluidPage(

   titlePanel("Old Faithful Geyser Data"),

   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# server

server <- function(input, output) {

   output$distPlot <- renderPlot({

      x    <- faithful[, 2] 
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      histogramaVermelho(x, breaks = bins)
   })
}

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

In addition, the archives app.R and histogramaVermelho.R must be in the same folder. If this is not possible, the file path histogramaVermelho.R in the system must be updated within the function source().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.