Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R shiny custom function

Tags:

r

shiny

I'm trying to call a reactive function within my custom function and I couldn't. What is the best way to do this, here is the simplified code and I can't pass everything as a functional parameter because there will be too many to pass.

  library(shiny); 
  myf<-function(){ return(psd()$y) }
  shinyApp( ui = textOutput("test2"), 
      server = function(input, output) {
          psd<-reactive({ return(data.frame(x=10,y=30)) })
          output$test2 <- renderText({ myf() })
        }
      )

This code generates an error : Error in myf() : could not find function "psd" What is the best way to call custom function which utilizes other function from within shinyserver?

like image 344
Sri Avatar asked Dec 11 '25 20:12

Sri


1 Answers

It depends if you want your function to be reactive as well or not.

In the case of reactivity use:

myf <- reactive({return(psd()$y})

If you don't want it to be reactive use

 myf <- function() {return(isolate(psd$y))}

Your reactive expression does not have a reactive Value (like input$). Therefore it does not get created. To understand reactivity better read this awesome instruction.


Furthermore maybe you try to avoid hardcoding and try to add the reactive function you want to call as a parameter in your function, like this:

myf<-function(func){ return(func()$y) }

And then:

output$test2 <- renderText({ myf(psd) })

like image 61
Kirill Avatar answered Dec 13 '25 11:12

Kirill