Home > Enterprise >  Is there a CRAN friendly way to have variables defined as a side-effect in R?
Is there a CRAN friendly way to have variables defined as a side-effect in R?

Time:07-12

Is there a way to use a function-call to set up a collection of variables with new names?

What I'd like is something like the following:

helper <- function (x) {
  y <<- x   1
  NULL
}

main <- function (x) {
  helper(x)
  return(y)  
}

However, there are two problems with this:

  • the code means that y is defined in the global environment, which I don't want;
  • I'm also aware that the <<- operator is not kosher as far as CRAN is concerned.

Essentially I'd like to make my function main cleaner by passing a lot of the work it does to helper. Is there any legitimate way to do this for a package that I eventually want to be on CRAN?

CodePudding user response:

I don't think your approach is in any way really sensible (why not use a List), but if you really want to do that, you can use assign to assign variables in arbitrary environments, e.g. the parent frame:

helper <- function(x) {
  assign('y', x   1, envir=parent.frame())
  NULL
}

main <- function(x) {
  helper(x)
  return(y)  
}

main(1)
# [1] 2

CodePudding user response:

You can use the strategy to have helper returning a list with the calculated variables and then use them:

helper <- function (x) {
  y <- x   1
  list(y = y)
}

main <- function (x) {
  vars <- helper(x)
  return(vars$y)  
}

If you are going to use y often and don't want to always type var$s, you could assign it locally:

main <- function (x) {
  vars <- helper(x)
  y <- vars$y
  return(y)  
}

In contrast to assigning variables in arbitrary environments, this makes it way easier to reason what your code does.

  • Related