Christoffer
Christoffer

Reputation: 661

Edit function in R using substitute with string as argument

I am trying to edit a function with the use of the body and substitute functions in R. I want to construct a new line for the function from a string and after that substitute it into the function.

I suppose that I need to convert the string to a certain class, which substitute can evaluate and feed into the function. But, I how can I do that?

Below is an example of what I want:

myFun <- function(x) {
    A1 <- 1
    A2 <- 10
    A1 <- x^2 + A2  # Line to be changed
    return(A1 + A2)
}

n <- 2
m <- 1
express_string <- paste0("A", n, " <- x^2 + A", m)

body(myFun)[[4]] <- substitute( express_string )  # This is the tricky part.

This is what I want the function to look like in the end:

myFun <- function(x) {
    A1 <- 1
    A2 <- 10
    A2 <- x^2 + A1  # New line
    return(A1 + A2)
}

Upvotes: 1

Views: 422

Answers (2)

Roland
Roland

Reputation: 132989

Just use parse:

body(myFun)[[4]] <- parse(text = express_string)[[1]]

Of course, it would be preferable to not create R command as strings. bquote can be helpful:

LHS <- as.name(paste0("A", n))
RHS <- as.name(paste0("A", m))

express <- bquote(.(LHS) <- x^2 + .(RHS))

body(myFun)[[4]] <- express 

Upvotes: 2

akrun
akrun

Reputation: 887951

We can parse the expression

body(myFun)[[4]] <- rlang::parse_expr(express_string)    
myFun
#function (x) 
#{
#    A1 <- 1
#    A2 <- 10
#    A2 <- x^2 + A1
#    return(A1 + A2)
#}

Upvotes: 2

Related Questions