1

As outlined here dataframes can have lists as columns. I try to do the same in Rcpp but without success.

df = data.frame(a=seq(1,2))
df$b = list(seq(1,10), seq(11,20))
df

My corresponding Rcpp example converts the resulting dataframe to a list (i.e. drops the dataframe attribute) - unintentionally:

cppFunction('
DataFrame testme() {
    DataFrame df = DataFrame::create(Named("a") = seq(1, 2));
    df["b"] = List::create(seq(1,10), seq(11,20));
    return df;
}')
testme()

Any ideas?

Egus
  • 121
  • 7

1 Answers1

1

I found a workaround based on this post:

cppFunction('
DataFrame testme1() {
    DataFrame df = DataFrame::create(Named("a") = seq(1, 2));
    df["b"] = List::create(seq(1,10), seq(11,20));
    df.attr("class") = "data.frame";
    df.attr("row.names") = Rcpp::seq(1, 2);
    return df;
}')
testme1()

I have to explicitly (re-)set the dataframe attribute after adding the list column to the dataframe.

Egus
  • 121
  • 7
  • Right, and glad you're sorted out. Your question is more or less a duplicate of that question. – Dirk Eddelbuettel Jan 14 '22 at 13:06
  • I wanted to create a dataframe with list columns directly (w/o using std::vector and creating a list first) and wondered that the attribute "dataframe" was dropped. However, I agree, the question is nearly duplicate. – Egus Jan 14 '22 at 14:34
  • The `DataFrame` support is fairly basic and has never been extended. If you dig you will find several posts (here, on the rcpp-devel list, ...) basically suggesting to _always_ work with `List` and only convert at the very end. Which, if you think about it, makes a lot of sense as only `List` are unconstrained. – Dirk Eddelbuettel Jan 14 '22 at 14:37