Created
June 10, 2014 12:21
-
-
Save simonohanlon101/519d6a90e1dca51cf7bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Rcpp.h> | |
#include <string> | |
#include <sstream> | |
using namespace Rcpp; | |
//[[Rcpp::export]] | |
NumericMatrix expandR(CharacterVector x) { | |
int n = x.size(); | |
std::vector< std::vector<int> > out; // list to hold numeric vectors | |
int tmax = 0; | |
for(int i = 0; i < n; ++i) { | |
std::vector<int> vect; // vector to hold split strings | |
std::string str = as<std::string>(x[i]); | |
std::stringstream ss(str); | |
int j = 0; | |
while (ss >> j) { | |
vect.push_back(j); // add integer to result vector | |
if (ss.peek() == ',') //split by ',' delim | |
ss.ignore(); | |
} | |
int it = *std::max_element(vect.begin(), vect.end()); | |
if( it > tmax ) | |
tmax = it; //current max value | |
out.push_back(vect); | |
} | |
// Now we construct the matrix. tmax gives us number of columns, n is number of rows; | |
NumericMatrix mat(n,tmax); | |
for( int i = 0; i < n; ++i) { | |
NumericMatrix::Row zzrow = mat( i , _ ); | |
std::vector<int> vec = out[i]; | |
for( int j = 0; j < vec.size(); ++j ) { | |
zzrow[ (vec[j]-1) ] = 1; //don't forget R vs. C++ indexing | |
} | |
} | |
return mat; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment