0

What would be the best practice when we would like to share variables across multiple sub-functions of same package (no need to update the content of those variables). e.g.

function1 <- function() {
  var1 <<- "x"
  var2 <<- "y"

  sub_function1()
  sub_function2()

}


sub_function1 <- function() {

  print(var1)

}

sub_function2 <- function() {

   print(var2)

}

Is it best practice to define global variables? I am just worried that if this package used in conjunction with other packages then global variables might interfere with each other. Is it best practice to pass as parameters?

morgan121
  • 2,213
  • 1
  • 15
  • 33
R007
  • 101
  • 1
  • 13
  • 3
    See https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r for some discussion of this. Personally I would say the best option is to use parameters. – Marius Feb 25 '20 at 23:28
  • Agree with @Marius; see in particular the answer by Paul Hiemstra which starts with *"In general global variables are **evil**. "* See also [Why are global variables evil?](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) for more details (it's a Python post but relevant to any language, as emphasised in the first answer). – Maurits Evers Feb 25 '20 at 23:33
  • thanks, that posts answer my question. – R007 Feb 25 '20 at 23:56

0 Answers0