On Apr 3, 2011, at 1:22 PM, Douglas Bates wrote:
On Sun, Apr 3, 2011 at 11:42 AM, David Winsemius <dwinsem...@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? :-)
Yes, I am now sufficiently confused^W , ... er, motivated to look for
another route. I think the way out of the confusion is to turn the
call into text and since as.character doesn't do a very neat a job, I
would suggest instead: deparse()
> fTest <- function(x) {
+ print(match.call())
+ list(x=x, logf = deparse(match.call()))
+ }
> fTest(x=3)$logf
fTest(x = 3)
[1] "fTest(x = 3)"
> cat(fTest(x=3)$logf)
fTest(x = 3)
fTest(x = 3)
cat() is a convenient test of the capacity of an object to be written
to a file. It has an append parameter that implies it could serve the
logging function requested by the OP.
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@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.