0

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 Answer 1

2

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: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

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 ~").
Yes, it works, but is there a way to create reactive function from that input? I want to plot it but also use it in other ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.