0

I have code inside the renderPlot option of a shiny app that I would like the pull into a separate reactive context. However, I'm having trouble figuring out how to do so and still be able to refer to the table.

What I want is to be able to pull the first section into it's own reactive context and then refer to it in the renderPlot, but I'm not sure how to do that considering the data source for the matrix is conditional on one of the inputs. Thanks in advance!

Current code:

output$distPlot <- renderPlot({
if (input$predictor == "bin") {matrix(0,ncol=1, nrow=input$n) -> predictor; predictor[1:input$pos] <- 1}
if (input$predictor == "norm") {predictor <- matrix(rnorm(input$n,input$pred_mean, input$pred_sd),ncol=1,nrow=input$n)}
if (input$predictor == "user") {inFile <- input$predictor2; predictor <- as.matrix(read.delim2(inFile$datapath, header=F), ncol=1)}
....
data <- sim(input$n,input$coverage[1], input$coverage[2], predictor)
....
})

Desired Code (conceptual)

predictor <- reactive({
if (input$predictor == "bin") {matrix(0,ncol=1, nrow=input$n) -> predictor; predictor[1:input$pos] <- 1}
if (input$predictor == "norm") {predictor <- matrix(rnorm(input$n,input$pred_mean, input$pred_sd),ncol=1,nrow=input$n)}
if (input$predictor == "user") {inFile <- input$predictor2; predictor <- as.matrix(read.delim2(inFile$datapath, header=F), ncol=1)}
}) 

output$distPlot <- renderPlot({
data <- sim(input$n,input$coverage[1], input$coverage[2], predictor)
....
})
Jautis
  • 459
  • 6
  • 13
  • To use a reactive, call it like a function `predictor()` – Xiongbing Jin Oct 18 '16 at 02:42
  • @warmoverflow Thanks! Could you also offer any advice on how I could define 'predictor'? The mock code I wrote won't work as predictor is only defined within 'reactive({...})', but input$predictor determines how predictor should be generated – Jautis Oct 18 '16 at 04:39
  • 1
    Just put `predictor <- NULL` at the beginning of the function, then add a line `predictor` at the end (that will return the `predictor` value when you call the function. – Xiongbing Jin Oct 18 '16 at 04:49

0 Answers0