Artie Ladie
Artie Ladie

Reputation: 521

How to return value from R Shiny Session

I read this tried solution from this question, but didn't work.

CherryPickPalette is an R function that takes in 2 to 3 color palettes, allows user to select their own colors, saves results to a file, scans the results into a variable.

Unfortunately, I am unable to read the variable.

Entire R script is here

When I execute script and exit it says number of items it read (based on user selection)

> CherryPickPalette("BiryaniRice","Kulfi","Haveli2")

Listening on http://127.0.0.1:4346
Read 7 items

However if I enter customcolors I get error

> customcolors
Error: object 'customcolors' not found

Below is function ... please guide.

CherryPickPalette <- function (name, name2=NULL, name3=NULL){

  # error checking    

  if (interactive()){
    colorfile <- paste(getwd(),"colorfile.txt",sep="/")
    if (!file.exists(colorfile)){
      file.create(colorfile)
    }
    shinyApp(
      ui = fluidPage(
        titlePanel("Cherry Pick Your Own Palette!"),
        sidebarPanel (hr(),
                      selectInput('col', 'Options', new_pal, multiple=TRUE, selectize=FALSE, size = 15)
                      ),
        mainPanel(
          h5('Your custom colors',style = "font-weight: bold;"),
          fluidRow(column(12,verbatimTextOutput("col"))))
      ),
      server = function(input,output,session){
        outuputdata<-  reactive({
          input$col
        })

        output$col <- { 
          renderPrint(outuputdata())
        }
        session$onSessionEnded(function(){
          message <- paste(isolate(outuputdata())," ")
          cat(message,file=colorfile, append=TRUE)
          customcolors <- scan(file=colorfile," ")

          # trying to return customcolors outside of shiny
          stopApp(customcolors)
          customcolors
          ######
        })
      }
    )
  }
}

Upvotes: 0

Views: 462

Answers (1)

Aur&#232;le
Aur&#232;le

Reputation: 12819

After running and closing the app:

customcolors <- scan("colorfile.txt", character())
customcolors

# [1] "#a96337" "#f0ecb0" "#4a4000" "#001a24"

Or run the app with:

customcolors <- runApp(CherryPickPalette("BiryaniRice","Kulfi","Haveli2"))

Upvotes: 2

Related Questions