Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over S4 object slots Rcpp

Tags:

r

rcpp

Is it possible to iterate over S4 object slots?

So far I was able to come up with this. But I would really like to avoid calling R function slotNames. Is there a possibility to do the same on 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
  }
}
like image 340
romants Avatar asked Mar 17 '23 12:03

romants


1 Answers

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

/**
 * R_has_slot() : a C-level test if a obj@<name> is available;
 *                as R_do_slot() gives an error when there's 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 you could drag it out with getAttrib.

So, today I learned that S4 slots are actually just special attributes, and these attributes are accessible with @. Observe:

> 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

Hopefully this gives you a place to get started, at least.

like image 173
Kevin Ushey Avatar answered Apr 01 '23 15:04

Kevin Ushey