How do I plot a function formatted as a string in R

190 views Asked by At

I am building an application with RApache and my code in R is receiving POST data. One of the post datas is POST$f which is a string- say "sin(x)". Is there any way to put this into the plot function successfully?

Thanks!

1

There are 1 answers

1
Brian Diggs On
fun <- "sin(x)"
plot(function(x) eval(parse(text=fun)))

But it is not something I would recommend. eval(parse(...)) is already dangerous, and then to do it with arbitrary user input from a web site is just a gaping security hole.

# PLOTTING THIS FUNCTION AS ABOVE WILL DELETE EVERYTHING IN YOUR GLOBAL WORKSPACE
fun <- "{rm(list=ls(pos=1),pos=1); x}"
# DON'T SAY I DIDN'T WARN YOU!

Or even using system() to do even more bad things.