xm1
xm1

Reputation: 1765

Why parent.frame(5)?

Can anyone help me counting the frames?
I have a shortcut to load function:

loa=function(x,dir='./dados/') { 
      if(right(dir,1) != '/') dir=paste0(dir,'/')
      tryCatch(load(paste0(dir,gsub('\"','',deparse(substitute(x))),'.rda'),envir = parent.frame(1))
       ,error= function(e) print(e)
       ,warning= function(e)
         load(paste0(dir,x,'.rda'),envir = parent.frame(5))
       )
}

In it, it is possible to put variable name without quotes, with quotes or a variable with the name. E.g., loa(VALE3) or loa('VALE3') or var_name='VALE3'; loa(var_name) works.
To make it work, I had to put parent.frame(5) - from 1 to 4 did not work. I can count .GlobalEnv, loa frame, tryCatch frame, even warningframe.
What are the other frames?

P.S.

right=function(x, n)  
   if(n>0) substr(x, (nchar(x)-n+1), nchar(x)) else substr(x, 1, (nchar(x)+n))

Upvotes: 0

Views: 347

Answers (1)

MrFlick
MrFlick

Reputation: 206207

Rather than using relative parent frames, it's much more direct to just capture the frame as the start of the function then pass that directly. (You don't have control over how many frames tryCatch created when it runs).

And while I think allowing either a string or a symbol name is really just a dangerous mess, R does allow it. You can inspect the type of the promise passed to the function and deparse it if it's not a string. It's would be better to have two different parameters. One if you want to pass a symbol, and a different one if you want to pass a character.

loa <- function(x, dir='./dados/') { 
      toenv <- parent.frame()
      xn <- substitute(x)
      if (!is.character(xn)) xn <- deparse(xn)
      if (right(dir,1) != '/') dir <- paste0(dir, '/')
      path <- paste0(dir,gsub('\"', '', xn), '.rda')
      tryCatch(load(path, envir = toenv), 
          error = function(e) print(e)
      )
}

Upvotes: 1

Related Questions