Jonathan
Jonathan

Reputation: 47

Connecting R Shiny to R Script with Function

I have a script called function.R which contains a function called my_function that generates an output.

my_function <- function(a, b, c) {
  # code
}

How can I get the user to input values for a,b,c in a r shiny app and then these inputs can be delivered to my function.R script. I want the shiny app to take in the inputs for each of these values (a,b,c) and then send it to my function.R script so it can show the output of my function in the r shiny app.

My r shiny app is

library(shiny)

source("/Users/havekqnsc/Desktop/function.R")

ui <- fluidPage(
  titlePanel("Function Output"),
  numericInput("a", "a", value = ""),
  numericInput("b", "b", value = ""),
  textInput("c", "c", value = ""),
  actionButton("Submit", "RunFunction")
)

server <- function(input, output) {
  observeEvent(input$Submit, {
    my_function()
  })
}

shinyApp(ui, server)

Upvotes: 2

Views: 718

Answers (1)

jpdugo17
jpdugo17

Reputation: 7116

  1. Call the function inside a reactive/eventReactive and store the result.
  2. Call the reactive inside a renderTable function.
library(shiny)

#example function
my_function <- function(a, b, c) {
  data.frame(a = a, b = b, c = c)
}
 
ui <- fluidPage(
  titlePanel("Function Output"),
  numericInput("a", "a", value = ""),
  numericInput("b", "b", value = ""),
  textInput("c", "c", value = ""),
  actionButton("Submit", "RunFunction"),
  tableOutput("result")
)

server <- function(input, output) {
  result <- eventReactive(input$Submit, {
    my_function(input$a, input$b, input$c)
  })
  
  output$result <- renderTable({
    result()
  })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions