0

I have this simple script.R which creates an empty Excel file:

my_script <- function() {
             data <- data.frame()
             write_xlsx(data, "my_excel.xlsx")
            }

I called it in the Shiny App with this code:

library(shiny)

source("my_script.R", local=TRUE)

ui <- fluidPage(
      tags$h1("New excel file")
      actionButton(button, "Make file")
      )

server <- function(input, output) {
          observeEvent(input$button, {
             source("my_script.R")
             })
          }

shinyApp(ui=ui, server=server)

When I run the app, the title and the button "Make file" appear correctly, but when I click the button, no file is created. I have put my_script.R it in the same directory of app.R. Where am I wrong?

P.s. I have already read these topics ( call R script from Shiny App How can I connect R Script with Shiny app in R? How to execute a long R script as function in RShiny and display the solution in the ui? ), but I couldn't find a solution.

Thanks in advance!

EmaK
  • 154
  • 1
  • 9
  • 1
    If your `source.R` file you define a function named `my_script`. When you run the source, that function is just created, it doesn't get called. I'm not sure why you have `source()` more than once. You can call it one at the top of your program, then call `my_script()` to actually run the code in the function you defined. In general you should not use `source()` to dynamically execute code. It's much better to use that just to define functions. Also if you call `write_xlsx` like that, it will write the file on the server. Is that what you want? – MrFlick Jul 05 '21 at 07:15
  • Many thanks MrFlick! It is the answer I was searching for! I have made the 2 errors you have underlined. By changing the path of the function "write_xlsx" from `write_xlsx(data, "my_excel.xlsx")` to the full path `write_xlsx(data_df,"/Users/Home/Desktop/app1/data_df.xlsx")` and by modifying the code in "server" from `source("my_script.R")` to `my_script()`, the app runs successfully! – EmaK Jul 06 '21 at 20:57

2 Answers2

0

Did you try to use the download button:

https://shiny.rstudio.com/reference/shiny/0.14/downloadHandler.html

Roelof Waaijman
  • 202
  • 1
  • 5
0

I have found the answer to my question in the comment of MrFlick. The right code is:

my_script <- function() {
             data <- data.frame()
             write_xlsx(data,"/Users/Home/Desktop/app1/data_df.xlsx") # <-- Added the full path of the output file
            }

and

library(shiny)

source("my_script.R", local=TRUE)

ui <- fluidPage(
      tags$h1("New excel file")
      actionButton(button, "Make file")
      )

server <- function(input, output) {
          observeEvent(input$button, {
             my_script()  # <-- Modified the call to the script
             })
          }

shinyApp(ui=ui, server=server)
EmaK
  • 154
  • 1
  • 9