0

I would like to import a spreadsheet file, run a complex r script on this file and then save the resulting dataframe. But I am not seeing how I would do this.

I have seen the question here: [Can R Shiny be used to import file, run R script, and export file](Can R Shiny be used to import file, run R script, and export file) Can R Shiny be used to import file, run R script, and export file?,

But I don't see 100% where the r script fits into this answer - the answer code does not specifically refer to r.script. Unfortunately this answer is closed.

Lets say the script file titled 'select_first_two_columns.r' was:

library(rio)
library(dplyr)

df <- import(import_file_name)
df2 <- df %>% select(1:2)
export(df2,"new_name.xlsx")

What would the shiny code look like? Yes I could write a function instead of an R script, but the actual R script is very complex and includes combining data from other sources. But ultimately the complex script starts with a file, makes a (big series of) transformation(s), and then exports a result file - hence the r script file.

I have tried a couple of approaches, but am a long way from a result that I would report. Some other answers refer to defining functions in r-script - I instead want to run the whole of the r script.

1 Answers1

1

Adapting the answer in the referenced link, using a simple R script to process the mtcars dataset and following call R script from Shiny App you could call your R script in the download handler like so:

Notes:

  • I would still suggest to rewrite your data analysis code using functions.

  • I dropped the data upload part for the sake of simplicity.

library(shiny)

ui <- fluidPage(
titlePanel("Data Transformation App"),
  sidebarLayout(
    sidebarPanel(
      downloadButton("download", "Process & Download", class = "action"),
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  data_uplood <- reactive({
    mtcars
  })
  
  output$download <- downloadHandler(
    filename = function() {
      paste("data-processed-", Sys.Date(), ".csv", sep = "")
    },
    content = function(con) {
      req(data_uplood())
      
      dat <- data_uplood()
      
      source("data-analysis.R", local = TRUE)
      
      write.csv(dat, con)
      
      output$contents <- renderTable({
        dat
      })
    }
  )
}

shinyApp(ui, server)

data-analysis.R

library(dplyr)

dat <- dat |>
  count(cyl)
stefan
  • 90,330
  • 6
  • 25
  • 51