Skip to content
Prev 393944 / 398500 Next

Trying to learn how to write an "advanced" function

The first thing to understand is that despite similarity in names,
`match` and `match.call` are doing very different things, which should
not be confused with each other.

For understanding what a function is doing, it is helpful to watch
what it does at each step.  With functions like `lm` that are built
in, we cannot easily modify the source code with print statements and
the like, then rerun, but the `trace` and `browser` functions are nice
for allowing us to debug these functions. If you run the following
line:

trace(lm, browser, at=7)

Then this will insert a call to `browser` into the `lm` function which
when you next run `lm` will pause at about line 7 (just after the code
that you show) and allow you to examine the values of `mf` and `m` and
any other variables.

Unfortunately just printing `mf` is not super helpful for this, since
it prettys the call, but printing as.list(mf) is more useful.
Basically mf will hold information on how `lm` was called, the first
element is that `lm` is the function that was called, then further
elements are the arguments that were passed in.

The line with `match` then identifies which elements of mf correspond
to the list of arguments that we want to keep for the next part
(essentially the next few lines create a call object to the
`model.frame` funcion with the same arguments that you passed to `lm`
but without any arguments not in the short list.

When in `browser` mode you can step through the evaluation of the
function with "s" or "n" and quit everything with "Q" (see ?browser
for details)

Don't forget to call `untrace(lm)` when you are through.
On Thu, Mar 16, 2023 at 6:16?AM Sorkin, John <jsorkin at som.umaryland.edu> wrote:

  
    
Message-ID: <CAFEqCdzT9Q5pxsu2vK1cTHPHiu+r=eCx62sE+NL3-WRR4aT4ug@mail.gmail.com>
In-Reply-To: <MW4PR03MB63630BA0F1173094445249BEE2BC9@MW4PR03MB6363.namprd03.prod.outlook.com>