I wonder if anyone can illustrate to me how R executes a C
call from an R command typed at the console prompt. I am particularly confused by R
\'s treat
The basic C-level pairlist extraction functions are CAR
and CDR
. (Pairlists are very similar to lists but are implemented as a linked-list and are used internally for argument lists). They have simple R equivalents: x[[1]]
and x[-1]
. R also provides lots of combinations of the two:
CAAR(x) = CAR(CAR(x))
which is equivalent to x[[1]][[1]]
CADR(x) = CAR(CDR(x))
which is equivalent to x[-1][[1]]
, i.e. x[[2]]
CADDR(x) = CAR(CDR(CDR(x))
is equivalent to x[-1][-1][[1]]
, i.e. x[[3]]
Accessing the nth element of a pairlist is an O(n)
operation, unlike accessing the nth element of a list which is O(1)
. This is why there aren't nicer functions for accessing the nth element of a pairlist.
Internal/primitive functions don't do matching by name, they only use positional matching, which is why they can use this simple system for extracting the arguments.
Next you need to understand what the arguments to the C function are. I'm not sure where these are documented, so I might not be completely right about the structure, but I should be the general pieces:
call
: the complete call, as might be captured by match.call()
op
: the index of the .Internal function called from R. This is needed because there is a many-to-1 mapping from .Internal functions to C functions. (e.g. do_summary
implements sum, mean, min, max and prod). The number is the third entry in names.c
- it's always 0 for do_setseed
and hence never used
args
: a pair list of the arguments supplied to the function.
env
: the environment from which the function was called.
checkArity
is a macro which calls Rf_checkArityCall
, which basically looks up the number of arguments (the fifth column in names.c
is arity) and make sure the supplied number matches. You have to follow through quite a few macros and functions in C to see what's going on - it's very helpful to have a local copy of R-source that you can grep through.