Skip to content

Instantly share code, notes, and snippets.

@hadley
Created November 11, 2012 14:40
Show Gist options
  • Save hadley/4055087 to your computer and use it in GitHub Desktop.
Save hadley/4055087 to your computer and use it in GitHub Desktop.
IntegerVector table1(const CharacterVector x) {
std::map<char*, int> counts;
int n = x.length();
for (int i = 0; i < n; i++) {
counts[x[i]]++;
}
// Loop through each element of map and output into named vector
IntegerVector out(counts.size());
CharacterVector names(counts.size());
std::map<char*, int>::iterator it;
int i;
for (i = 0, it = counts.begin(); it != counts.end(); i++, it++) {
names[i] = it->first;
out[i] = it->second;
}
out.attr("names") = names;
return(out);
}
library(Rcpp)
cppFunction('
IntegerVector table1(const CharacterVector x) {
std::map<std::string, int> counts;
std::vector<std::string> vec = as<std::vector<std::string> >(x);
int n = x.length();
for (int i = 0; i < n; i++) {
counts[vec[i]]++;
}
// Loop through each element of map and output into named vector
IntegerVector out(counts.size());
CharacterVector names(counts.size());
std::map<std::string, int>::iterator it;
int i;
for (i = 0, it = counts.begin(); it != counts.end(); i++, it++) {
names[i] = it->first;
out[i] = it->second;
}
out.attr("names") = names;
return(out);
}
')
library(microbenchmark)
x <- sample(letters, 1e4, rep = T)
microbenchmark(
table(x),
table1(x)
)
# About 3x faster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment