NeilC
NeilC

Reputation: 188

Pass code to an R function as an argument

I'd like to create an R function that is a 'helper' for users to make their own, new function. The user passes code as an argument and it gets incorporated into a new function.

I'm pretty sure this needs non-standard evaluation and I've checked previous StackOverflow answers as well as the NSE chapter in Advanced R but just can't crack it. Does anyone know how to make the following code work and return 3?

create_new_function <- function(f){
  task <- function(a, b){
    f  #how do I make f evaluate here as a+b?
  }
  
  return(task)
}


user_function <- create_new_function(a+b)

user_function(1,2)

I don't want the user to have to pass (a,b) when the function is created, but to have access to them when it is called, which is why it's nested.

Upvotes: 1

Views: 331

Answers (1)

fardarter
fardarter

Reputation: 136

create_new_function <- function(f){
  express <- substitute(f)
  task <- function(a, b){
    return(eval(express))
  }
  return(task)
}

user_function <- create_new_function(a+b)

print(user_function(1,2))

Upvotes: 2

Related Questions