Allocating a string to a function in R
I have a Shiny app in R where I want users to be able to create functions on the fly by entering text into a text box. To enable this feature, I would like to know the following:
How can I put a string object containing the definition of a function in an actual function by binding it to a variable name?
For example:
function_code = 'function(x) { as.dist(1-cor(t(x))) }'
f = something(function_code, ...)
Where something()
converts function_code
to a valid function and assigns it to a variable f
. I don't think I can use function_code
in a function directly, and I tried to use as.function
and that didn't work either.
Thank!
source to share
You can use parse()
and eval()
:
foo <- eval(parse(text = function_code))
> foo
function(x) { as.dist(1-cor(t(x))) }
Just wrap this in a function:
parseEval <- function(text) {
eval(parse(text = text))
}
If you want an actual something()
, not a direct call.
Here's an example:
set.seed(1)
x <- matrix(runif(20), ncol = 2)
out <- foo(x)
Providing
> zapsmall(out)
1 2 3 4 5 6 7 8 9
2 0
3 2 2
4 0 0 2
5 2 2 0 2
6 0 0 2 0 2
7 0 0 2 0 2 0
8 2 2 0 2 0 2 2
9 0 0 2 0 2 0 0 2
10 2 2 0 2 0 2 2 0 2
source to share
You may try
input <- list()
input$f <- "x^2 + 2"
f <- function(x) eval(parse(text = input$f)) # text to function
f(2)
# [1] 6
This way your user doesn't need to write the part function(x)
. However, when you do this, your program is vulnerable if the user adds system calls ( system
).
source to share