简体   繁体   中英

Passing objects to functions

I am currently working on user defined functions aimed at modelling empirical data and I have problems with objects / parameters passed to the function:

bestModel <- function(k=4L, R2=0.994){
  print(k)   # here, everything is still fine

  lmX <- mixlm::lm(getLinearModelFunction(k), data)
  best <- mixlm::best.subsets(lmX, nbest=1)
  .
  .
  .
}

At first, everything works as expected, but as soon as I want to pass the parameter k to another user defined function getLinearModelFunction() , an error is thrown:

Error in getLinearModelFunction(k) : object 'k' not found 

It doesn't help, if I am assigning a new parameter, eg l <- k and try to pass that on. The parameter doesn't seem to be available for the other function. I ran into this problem not only with primitive data types, but as well complex structures. On command line, everything works, as long as the objects are in my workspace.

To sum it up: Passing parameters work only within that function, but calls of other functions from there onwards result in error. Why? And: What to do about it?

EDIT: While trying to resolve the problem, it gets really weird. I stripped down all functions:

functionA <- function(data, k){
      lmX <- mixlm::lm(functionB(k), data)
      summary(lmX)

      # best <- mixlm::best.subsets(lmX,nbest=1)
    }


    functionB <- function(k=4){
      if(k==1){
        return(formula("raw ~ L1"))
      }else if(k==2){
        return(formula("raw ~ L1 + L2"))
      }else if(k==3){
        return(formula("raw ~ L1 + L2 + L3 "))
      }else if(k==4){
        return(formula("raw ~ L1 + L2 + L3 + L4"))
      }
    }

Let's say, we have a data.frame d with the variables raw, L1, L2, L3, L4 ... As long, as there is the commenting # before best, it works. As soon as it is removed, calling functionA(d, 3) results in

Error in functionB(k) : object 'k' not found  

Even, though k doesn't play a role in that function and before that, it worked.

Ok, indeed, this was an environment thing. The solution is to get the current environment and to take the object from there:

functionA <- function(data, k){
   e <- environment()
   lmX <- mixlm::lm(functionB(e$k), e$data)
   summary(lmX)

   best <- mixlm::best.subsets(lmX,nbest=1)
 }

This is usually not a problem, when directly working with are packages. The objects usually are in the global environments then. When working with functions, each function has its' own environment. I managed to solve this while starting to learn about packaging the code: http://adv-r.had.co.nz/Environments.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM