[R] converting "call" objects into character

Douglas Bates bates at stat.wisc.edu
Sun Apr 3 19:22:24 CEST 2011


On Sun, Apr 3, 2011 at 11:42 AM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Apr 3, 2011, at 12:14 PM, Samuel Le wrote:
>
>> Dear all,
>>
>>
>>
>> I would like to log the calls to my functions. I am trying to do this
>> using the function match.call():
>
> fTest<-function(x)
>
> {  theCall<-match.call()
>      print(theCall)
>      return(list(x=x, logf = theCall))
> }
>
>>
>> fTest(x=2)$x
> [1] 2
>> fTest(x=2)$logf
> fTest(x = 2)
>> str(fTest(x=2)$logf)
>  language fTest(x = 2)
>
> You may want to convert that  call component to a character object, since:
>
>> cat(fTest(x=2)$logf)
> Error in cat(list(...), file, sep, fill, labels, append) :
>  argument 1 (type 'language') cannot be handled by 'cat'

If you want to examine a call object you need to ensure that it is not
evaluated.  Evaluating a number or a character string is not a problem
because

eval(4)

is the same as

4

However, evaluating a function call should be different from the call
itself.  As David shows, the str function is careful not to evaluate
the call object.  (Martin and I found ourselves going around in
circles when looking at the structure of a fitted model object that
included a call and he kindly changed the behavior of str().)

So you need to decide when a function, such as print(), evaluates its
arguments or when it doesn't, which can get kind of complicated.  An
alternative is to use match.call() repeatedly instead of trying to
save the value, as in

> fTest
function(x) {
    print(match.call())
    list(x=x, logf = match.call())
}
> fTest(x=2)
fTest(x = 2)
$x
[1] 2

$logf
fTest(x = 2)

The trick there is that the value of match.call() is the unevaluated
call whereas

myCall <- match.call()
print(myCall)

evaluates myCall in the call to print, thereby evaluating the function
fTest again.

Is this sufficiently confusing?  :-)


>>
>> I can see "theCall" printed into the console, but I don't manage to
>> convert it into a character to write it into a log file with other
>> informations.
>>
>> Can anyone help?
>
>
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list