Skip to content

Instantly share code, notes, and snippets.

View hadley's full-sized avatar

Hadley Wickham hadley

View GitHub Profile
df <- setNames(as.data.frame(matrix(nrow = 0, ncol = 2)), c("x", "y"))
# Works
qplot(x, y, data = df)
qplot(x, y, data = df, geom = "smooth")
qplot(x, y, data = df, geom = "density")
# Doesn't work
qplot(x, data = df, geom = "density")
{
baseball_df <- data_frame_source(baseball)
baseball_dt <- data_table_source(baseball)
baseball_s <- sqlite_source("inst/db/baseball.sqlite3", "baseball")
}
ddply(baseball, "id", summarise, g = mean(g))
#: user system elapsed
#: 0.499 0.003 0.503
summarise_by(baseball_s, group("id"), list(g = quote(mean(g))))
sign1 <- function(x) {
if (x > 0) {
1
} else if (x == 0) {
0
} else {
-1
}
}
set_env <- function(envs) {
stopifnot(is.named(envs))
old <- Sys.getenv(names(envs), names = TRUE, unset = NA)
set <- !is.na(envs)
if (any(set)) do.call("Sys.setenv", as.list(envs[set]))
if (any(!set)) Sys.unsetenv(names(envs)[!set])
invisible(old)
library(Rcpp)
cppFunction('
NumericVector my_diff(NumericVector x, const int lag) {
NumericVector y(x.length() - lag);
int n = x.length();
for (int i = lag; i < n; i++) {
y[i - lag] = x[i] - x[i - lag];
}
return(y);
}'
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());
cppFunction('
#include <algorithm>
IntegerVector findInterval2(NumericVector x, NumericVector breaks) {
IntegerVector out(x.size());
NumericVector::iterator it, pos;
IntegerVector::iterator out_it;
for(it = x.begin(), out_it = out.begin(); it != x.end(); it++, out_it++) {
pos = std::upper_bound(breaks.begin(), breaks.end(), *it);
// [[Rcpp::export]]
LogicalVector duplicated3(IntegerVector x) {
std::set<int> seen;
LogicalVector out(x.size());
IntegerVector::iterator it, end = x.end();
LogicalVector::iterator out_it;
for (it = x.begin(), out_it = out.begin(); it != end; ++it, ++out_it) {
#include <Rcpp.h>
using namespace Rcpp;
double vacc3a(double age, int female, int ily){
double p = 0.25 + 0.3 * 1 / (1 - exp(0.004 * age)) + 0.1 * ily;
p = p * (female ? 1.25 : 0.75);
p = max(p, 0.0);
p = min(p, 1.0);
return p;
}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double vacc3a(double age, bool female, double ily){
double p = 0.25 + 0.3 * 1 / (1 - exp(0.04 * age)) + 0.1 * ily;
p = p * (female ? 1.25 : 0.75);
p = std::max(p, 0.0);
p = std::min(p, 1.0);
return p;