Iterate over S4 Rcpp object slots

Is it possible to repeat the iteration over the slots S4?

So far I have managed to do this. But I really would like to avoid calling the R function slotNames. Is it possible to do the same at the C / C ++ level?

// [[Rcpp::export]]
void foo(SEXP x) {
  Rcpp::S4 obj(x);
  Function slotNames("slotNames"); 
  CharacterVector snames = slotNames(obj);
  for (int i = 0; i < snames.size(); i++) {
    SEXP slot = obj.slot(Rcpp::as<std::string>(snames[i]));
    // do something with slot
  }
}
+4
source share
1 answer

Looking at the source code for R, I see things like this:

/**
 * R_has_slot() : a C-level test if a obj@<name> is available;
 *                as R_do_slot() gives an error when there no such slot.
 */
int R_has_slot(SEXP obj, SEXP name) {

#define R_SLOT_INIT                         \
    if(!(isSymbol(name) || (isString(name) && LENGTH(name) == 1)))  \
    error(_("invalid type or length for slot name"));       \
    if(!s_dot_Data)                         \
    init_slot_handling();                       \
    if(isString(name)) name = installChar(STRING_ELT(name, 0))

    R_SLOT_INIT;
    if(name == s_dot_Data && TYPEOF(obj) != S4SXP)
    return(1);
    /* else */
    return(getAttrib(obj, name) != R_NilValue);
}

Which, I suppose, implies that you could drag it with getAttrib.

So, today I found out that S4 slots are actually only special attributes, and these attributes are available with @. Note:

> setClass("Foo", list(apple = "numeric"))
> foo <- new("Foo", apple = 1)
> foo@apple
[1] 1
> attributes(foo)
$apple
[1] 1

$class
[1] "Foo"
attr(,"package")
[1] ".GlobalEnv"

> foo@class
[1] "Foo"
attr(,"package")
[1] ".GlobalEnv"
> attr(foo, "bar") <- 2
> foo@bar
[1] 2

Hope this gives you a place to start, at least.

+5

All Articles