[R] determining a parent function name

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Thu May 31 15:13:56 CEST 2007


Hi, Vladimir,

In general, this won't work since traceback only contains the stack from 
the last uncaught error (see ?traceback). When traceback is called below 
it would be from the previous error, not the current one.

error <- function() {
   parent <- tail(capture.output(traceback()), n = 1)
   parent <- sub("^.*:[ ]+", "", parent)
   stop(parent)
}
foo <- function() error()
bar <- function() error()

 > foo()
Error in error() : No traceback available
 > bar()
Error in error() : foo()

Thanks,

--sundar

Vladimir Eremeev said the following on 5/31/2007 4:57 AM:
> Does
>   tail(capture.output(traceback()),n=1)
> do what you want?
> 
> that is 
> 
> error <- function(...) {
>    msg <- paste(..., sep = "")
>    if(!length(msg)) msg <- ""
>    if(require(tcltk, quiet = TRUE)) {
>      tt <- tktoplevel()
>      tkwm.title(tt, "Error")
>      tkmsg <- tktext(tt, bg = "white")
> 
>      parent<-tail(capture.output(traceback()),n=1)
>      parent<-gsub("[0-9]: ","",parent) # deleting 1: from the captured
> string
> 
>      tkinsert(tkmsg, "end", sprintf("Error in %s: %s", parent , msg))
>      tkconfigure(tkmsg, state = "disabled", font = "Tahoma 12",
>                  width = 50, height = 3)
>      tkpack(tkmsg, side = "bottom", fill = "y")
>    }
>    stop(msg)
> }
> 
> 
> Sundar Dorai-Raj wrote:
>> Hi, All,
>>
>> I'm writing a wrapper for stop that produces a popup window using tcltk. 
>> Something like:
>>
>> error <- function(...) {
>>    msg <- paste(..., sep = "")
>>    if(!length(msg)) msg <- ""
>>    if(require(tcltk, quiet = TRUE)) {
>>      tt <- tktoplevel()
>>      tkwm.title(tt, "Error")
>>      tkmsg <- tktext(tt, bg = "white")
>>      tkinsert(tkmsg, "end", sprintf("Error in %s: %s", "???", msg))
>>      tkconfigure(tkmsg, state = "disabled", font = "Tahoma 12",
>>                  width = 50, height = 3)
>>      tkpack(tkmsg, side = "bottom", fill = "y")
>>    }
>>    stop(msg)
>> }
>>
>> But, I would like to know from which function error() is called. For 
>> example, if I have
>>
>> foo <- function() stop()
>> bar <- function() error()
>>  > foo()
>> Error in foo() :
>>  > bar()
>> Error in error() :
>>
>> and in the tk window I get
>>
>> Error in ???:
>>
>> I need the output of bar (in the tk window only) to be
>>
>> Error in bar():
>>
>> then it's clear where error is called. I'm not worried about the output 
>> bar() produces on the console.
>>
>> Hope this makes sense.
>>
>> Thanks,
>>
>>
>



More information about the R-help mailing list