From edd at debian.org  Sat Aug 10 18:41:39 2013
From: edd at debian.org (Dirk Eddelbuettel)
Date: Sat, 10 Aug 2013 11:41:39 -0500
Subject: [Rd] Creating data.frame from c-language
In-Reply-To: <52063D7E.7000009@stats.ox.ac.uk>
References: <9D80368C6A00834189C1982FB64EFA3007ED8670@ORD2MBX07C.mex05.mlsrvr.com>
	<52063D7E.7000009@stats.ox.ac.uk>
Message-ID: <20998.27971.266792.578650@max.nulle.part>


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



[Rd] Creating data.frame from c-language
Dirk Eddelbuettel