Warning when a global variable is used?

I'm working on an R function that doesn't have all of it's inputs specified at the function call, that is to say, it uses a lot of global variables (parameter values to a model), making things hard to debug.

Is there a way to find all these uses using some tooling? Like a warning of some kind?

Furthermore, what's the best way to refactor this? Pass a list of parameters to the function?

Thanks!

I think enabling RStudio's Code Diagnostics would help you with this situation.

As for your second question, I would say that if your function is so huge and complex that it's hard to even keep track of what parameters it takes, then it's seriously worth considering breaking it into smaller, more manageable functions.

1 Like

Thank you! This is exactly what I was looking for! Now I have a bunch of yellow symbols to inspect on the side of my screen.

Yes, smaller functions might be a goal, but I'm just getting started on this code base so I won't do anything that drastic yet.

Two thoughts.

  1. Put the global variables in the function header as default values.
myfunc <- function(x, y, ga = globala, gb = globalb){ 
  ... ga
  ... gb 
}
  1. Only access the global variable explicitly using the get() function
myfunc <- function(x, y){ 
  ga <- get("globala", envir = globalenv())
  gb <- get("globalb", envir = globalenv())
  ... ga
  ... gb
}

Thanks, I think I will go with option 2, since I just want to be explicit in the code and not change the function definition too much.

Following up with this,

I am now writing my own code for this, so I get to re-think some things.

What are the current best practices for organizing model parameters doing model fitting in R? I am an economist so it's things like alpha_L, alpha_K, elasticities etc.

EDIT: I mean for estimating an economic model using some sort of Iterative method, where I need to make assumptions about the values of something like the labor share, nothing to do with a model like OLS.

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