Returning from a sub function

I'm trying to write a function which will cause its parent function to return a value. Here is the reprex:

test <- function(data) {
  val <- checkForValue(data)
  if (!isFALSE(val)) {
    return(val)
  }
  return("bar")
}

checkForValue <- function(data) {
  if ("test" %in% names(data)) {
    return(data[["test"]])
  }
  return(FALSE)
}

mtcars$test <- "foo"
test(mtcars)

This all works, but I'd like to have checkForValue cause test to return directly rather than doing the if/else dance

Hi,

I might be missing something, but I think this will suffice:

test <- function(data){
  if ("test" %in% names(data)) {
    return(data[["test"]])
  }
  return("bar")
}

mtcars$test <- "foo"
test(mtcars)

Hope this helps,
PJ

Oh yes, but in this case I actually want the sub function, the idea is to write a sub function that does that return and allows me to call it in a bunch of other functions.

Hey @gordon, interesting question.

To my knowledge, you can't do exactly what you're asking (cause one function to return from another's body). But your code above is effectively doing that when the inner function returns a value that causes an early return of the outer function. I see and write code similar to this all the time.

Thanks for producing the reprex, but I wonder if sharing an example that more closely resembles the code you're working on my help clarify things?

1 Like

I figured it out!

test <- function(data) {
  eval(checkForValue(data))
  return("bar")
}

checkForValue <- function(data) {
  if ("test" %in% names(data)) {
    assign("return_data", data[["test"]], parent.frame())
    out <- rlang::expr(print(return_data))
    return(out)
  }
}
1 Like

This site has much to recommend it, including civility, helpfulness, openness to interesting questions and debate.

But it really shines in situations where the dialogue leads a poster of a problem to their own solution, and the poster shares it.

Please be sure to mark it as the "solution" for the benefit of future pilgrims. No false modesty.

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