GeezerVison is showing github.com — Strongly typed data frame · Issue #198 · Rcpp11/Rcpp11
Strongly typed data frame #198
Description
The DataFrame is not as useful as it could be because it lacks information about each of the column. Would be interesting to embed column type information, e.g. Df<int, double> for a data frame that has an integer vector and a numeric vector. The code below is a quick experiment allowing this syntax:
Df<int,double> data(5) ;
for( int i=0; i<5; i++){
data[i] = std::make_tuple(i, sqrt(i) ) ;
}
return data ;
So the first line expresses that we want a data frame with these scalar types (int, double). Then we use the set method to set values for index i.
#include <Rcpp11>
using namespace Rcpp11 ;
template <typename... Pack>
void nothing( Pack...){}
template <typename... Args>
class Df {
public:
typedef typename Rcpp::traits::index_sequence<Args...>::type Sequence ;
typedef std::tuple< typename Rcpp::traits::vector_of<Args>::type ... > Tuple ;
typedef std::tuple<Args...> ETuple ;
Df( int n ) : data( init( n, Sequence() ) ){}
inline operator SEXP(){
return Rcpp::DataFrame( get( Sequence() ) );
}
class Proxy {
public:
Proxy( Df& df_, int i_) : df(df_), i(i_) {}
inline operator ETuple() const {
return get_all( Sequence() ) ;
}
inline Proxy& operator=( ETuple x ){
set_all( x, Sequence() ) ;
return *this ;
}
private:
template <int... S>
inline void set_all( ETuple x, Rcpp::traits::sequence<S...> ){
nothing( ( std::get<S>(df.data)[i] = std::get<S>(x) ) ... ) ;
}
template <int... S>
inline ETuple get_all( Rcpp::traits::sequence<S...> ){
return ETuple( std::get<S>( df.data ) ... ) ;
}
Df& df ;
int i ;
} ;
inline Proxy operator[](int i){
return Proxy(*this, i );
}
Tuple data ;
template <int... S>
Tuple init( int n, Rcpp::traits::sequence<S...> ){
return Tuple( typename std::tuple_element<S,Tuple>::type(n) ... ) ;
}
template <int... S>
List get( Rcpp::traits::sequence<S...> ){
return list( std::get<S>(data)... ) ;
}
} ;
// [[Rcpp::export]]
SEXP test(){
Df<int,double> data(5) ;
for( int i=0; i<5; i++){
data[i] = std::make_tuple(i, sqrt(i) ) ;
}
return data ;
}
/*** R
test()
*/
Metadata
Metadata
Development
No branches or pull requestsIssue actions