On 14 May 2011 at 23:12, Nick Sabbe wrote: | I?ve been trying the following, with the main part ripped from rcpp-quickref: | | SEXP dfr2Mat(SEXP dfr)
A much easier way is to, say, call as.matrix() in R and then assign to an NumericMatrix object in C++. Another way is turn the Data.Frame into a list via as.list() as just pick off column after column. | { | DataFrame df = dfr; | int* dm = INTEGER( ::Rf_getAttrib( df, R_DimSymbol ) ) ; | int rows = dm[0]; | int cols = dm[1]; | NumericMatrix retMat (rows, cols); | for(int i = 0; i < cols; i++) | { | NumericVector curcol = df(i); | NumericMatrix::Column cl = retMat.( _, i); Why is retMat on the right-hand side if you try to fill it? Makes no real sense. | cl = curcol; | } | return retMat; | } I can see no straightforward way to write given how objects are organized internally. Once a Rcpp::DataFrame object is instantiated, you can call size() which gives you the number of columns. So here is a really complicated way to do this, but let me reiterate that I think you are starting from the wrong starting point: if your data.frame really is a matrix, just use a matrix: R> require(inline) Loading required package: inline R> R> df2mat <- cxxfunction(signature(Dsexp="ANY"), plugin="Rcpp", body=' + // construct the data.frame object + Rcpp::DataFrame DF = Rcpp::DataFrame(Dsexp); + + // we get ncol() from DF + int k = DF.size(); + + // but for nrow() we need to assign first; one way is: + Rcpp::NumericVector V = DF[0]; + int n = V.size(); + + Rcpp::NumericMatrix M(n,k); + + for (int i=0; i<k; i++) { + V = DF[i]; + M(_,i) = V; // one way to assign using sugar operator _ + } + + return M; + ') R> M <- df2mat(data.frame(a=1:5, b=seq(1.1,5.5,by=1.1))) R> M [,1] [,2] [1,] 1 1.1 [2,] 2 2.2 [3,] 3 3.3 [4,] 4 4.4 [5,] 5 5.5 R> class(M) [1] "matrix" R> Hope this helps, Dirk -- Gauss once played himself in a zero-sum game and won $50. -- #11 at http://www.gaussfacts.com _______________________________________________ Rcpp-devel mailing list Rcpp-devel@lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel