How to return dataframe with columns being lists using Rcpp?
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?
Solution 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.