[Rd] Creating data.frame from c-language

Dirk Eddelbuettel edd at debian.org
Sat Aug 10 18:41:39 CEST 2013


On 10 August 2013 at 14:17, Prof Brian Ripley wrote:
| On 09/08/2013 22:48, Boris Aronshtam wrote:
| > I need to create a data.frame from C-language and populate it. I Know how to create lists from C, but I cannot figure out how to create a data.frame. Does anyone have a sample code for creating a data.frame, setting column names, and populating it with data?
| 
| Use data.frame() via an eval() call from C.
|
| Or see the code is stats/src/model.c, as part of model.frame.default 
| (but I would only do that if speed were essential).

Or if C++ is an option for you, below if a six-line Rcpp source example:

R> sourceCpp("/tmp/dataframe.cpp")   ## see the file below
R> set.seed(42);  getDataFrame(5)    ## set RNG seed, request a dataframe
          a        b
1  1.370958 0.457742
2 -0.564698 0.719112
3  0.363128 0.934672
4  0.632863 0.255429
5  0.404268 0.462293
R> 
 
The source file used above follows below.

Dirk


#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
DataFrame getDataFrame(int n) {
  NumericVector a = rnorm(n);
  NumericVector b = runif(n);
  return DataFrame::create(Named("a") = a,
			   Named("b") = b);
}
    



-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com



More information about the R-devel mailing list