[R] getPairListElement()

Greg Minshall minshall at acm.org
Mon Jun 30 09:06:04 CEST 2014


hi.  "Writing R Extensions" provides a simple routine getListElement(),
said to be based on a similar routine in the package stats, for C code
to call to find a named element of a list .  however, it doesn't work
for the argument list passed to a .External(), as that is a PairList
rather than a List.

below is a simple reworking (with slightly different semantics) that
appears to work with PairLists.  the argument "cmd" is used in producing
an error() in the case where this the requested element is not found.
(the original getListElement() would return R_NilValue, but for *my* use
i found throwing the error easier at this lower level; possibly i should
have parameterized that behavior.)

here is an example of use:
----
static SEXP
rimageread(SEXP args) {
...
  file = CHAR(STRING_ELT(getPairListElement(args, "file", "rimageread"), 0));
  usemagick = LOGICAL(getPairListElement(args, "usemagickwand", "rimageread"))[0];
...
}
----

anyway, in the hope this may be of some use to someone.

cheers, Greg Minshall
----
/* get the list element named str, or report an error() */
static SEXP
getPairListElement(SEXP pairs, const char *str, const char *cmd) {
    for (pairs = CDR(pairs); pairs != R_NilValue; pairs = CDR(pairs)) {
        if (!isNull(TAG(pairs))) {
            if (strcmp(CHAR(PRINTNAME(TAG(pairs))), str) == 0) {
                return CAR(pairs);
            }
        }
    }
    error("%s: required parameter '%s' not specified", cmd, str);
    /*NOTREACHED*/
}



More information about the R-help mailing list