Pass a `chr` type argument and update the content of a nested function to return in R

Cross posted from stackoverflow

For a nested function such as

fun_parent <- function(var) {
  fun_child <- function(x) {
    x + var
  }
  return(fun_child)
}

How can I customize the content of the returned function fun_child based on the input var?
For example,

test <- fun_parent(var = "y")
print(test)

Desirable output:

function(x) {
  x + y
  }
<environment: xxxxxx>

Actual (undesirable) output:

function(x) {
    x + var
  }
<environment: 0x7f7f20126b70>

Any help would be greatly appreciated!

Hi,

Here is one solution, but it's not very elegant

fun_parent <- function(var) {
  fun_child <- eval(parse(
    text = sprintf("function(x) {x + %s}", var)
  ))
  return(fun_child)
}

fun_parent("y")
#> function(x) {x + y}
#> <environment: 0x000000001e39a7a0>

Created on 2022-01-13 by the reprex package (v2.0.1)

I used string substitution and evaluation to get the desired result, but the whole function needs to be in text format which will become impractical for larger functions. There might be a cleaner way of doing this, especially maybe with TidyEval, but I'm not very good at this stuff :slight_smile:

Hope this helps,
PJ

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.