-->

Shiny - Create reactive function from user string

2020-08-01 07:20发布

问题:

I'm writing shiny app and I want to create mathematical functions from user input - There is textInput where user writes a function, e.g x^2, sin(x)+5 etc. Then, I want to plot this function so I have to concatenate string from textInput and 'function(x)' statement to get R function. As far as I know, I need to have reactive variable which contains the R function. I came up with that:

func<-reactive(
     bquote(function(x){ .(parse(text = input$fun)[[1]])}), quoted = TRUE
)

where input$fun is id of textInput. This solution doesn't work and I have no other idea.

回答1:

You can use f<-function(x) {eval(parse(text=input$func))} to transform the input into a function.

Fron @JoeCheng:

While this certainly works, I'd caution anyone reading this to only use eval() on user input if the app will only be run locally. Apps that do this are not safe to deploy on a server because a user could feed in whatever code they want, for example system("rm -rf ~")

For example, in a shiny app:

app.R

library(shiny)

        ui <- shinyUI(fluidPage(
                mainPanel(textInput("func", "Function:", ""),
                          submitButton("Plot!"),
                          plotOutput("plot")
                          )
        ))
        server <- function(input, output, session) {
                output$plot<-renderPlot({
                        f<-function(x) {eval(parse(text=input$func))}
                        x<-1:10
                        plot(x,f(x))
                }                        
                )              
        }

shinyApp(ui = ui, server = server)

Would give you this:



标签: r shiny