Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R convert text field to function

Tags:

r

I want to use information from a field and include it in a R function, e.g.:

data #name of the data.frame with only one raw

"(if(nclusters>0){OptmizationInputs[3,3]*beta[1]}else{0})" # this is the raw

If I want to use this information inside a function how could I do it?

Another example:
A=c('x^2')
B=function (x) A
B(2)
"x^2"  # this is the return. I would like to have the return something like 2^2=4.
like image 656
Eliano Avatar asked Jun 05 '26 11:06

Eliano


1 Answers

Use body<- and parse

A <- 'x^2'

B <- function(x) {}

body(B) <- parse(text = A)

B(3)
## [1] 9

There are more ideas here

like image 77
mnel Avatar answered Jun 07 '26 23:06

mnel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!