Skip to content

Instantly share code, notes, and snippets.

Avatar

Hadley Wickham hadley

View GitHub Profile
View self-modification.r
next_letter <- local({
i <- 0
function() {
i <<- i + 1
paste0("x_", c(letters, LETTERS))[i]
}
})
f <- function() {
new_arg <- alist(x = )
View round-3-ggplot2.r
library("Quandl")
library("ggplot2")
library("reshape2")
hist_rev <- Quandl("TPC/HIST_RECEIPT",
start_date = "1945-12-31",
end_date = "2013-12-31")
# melt into tidy (http://vita.had.co.nz/papers/tidy-data.html) form
hist_revm <- melt(hist_rev, id = "Fiscal Year")
View geocode.r
# This script uses httr to download data from Google's API
# Notice ther is a limit of 2,500 calls per day
library(httr)
base_url <- "http://maps.google.com/maps/api/geocode/json"
geoCode <- function(address,verbose=FALSE) {
r <- GET(base_url, query = list(address = address, sensor = "false"))
stop_for_status(r)
View is_installed.r
is_installed <- function(pkg, version = NULL) {
system.file(package = pkg) != "" && version_ok(pkg, version)
}
version_ok <- function(pkg, version = NULL) {
if (is.null(version)) return(TRUE)
pkgVersion(pkg) >= version
}
@hadley
hadley / rng-streams.R
Last active Aug 29, 2015
Manage multiple independent streams of random numbers
View rng-streams.R
get_seed <- function() {
if (!exists(".Random.seed", envir = globalenv())) return(NULL)
get(".Random.seed", envir = globalenv())
}
set_seed <- function(x) {
old <- cur_seed()
if (!is.null(x)) {
assign(".Random.seed", x, envir = globalenv())
}
View png.r
png <- function(path, dpi = NULL) {
meta <- attr(png::readPNG(path, native = TRUE, info = TRUE), "info")
if (!is.null(dpi)) meta$dpi <- rep(dpi, 2)
meta$path <- path
structure(meta, class = "png")
}
knit_print.png <- function(x, options) {
str(options)
knitr::asis_output(paste0(
View topwords.R
#!/usr/bin/env Rscript
n <- as.integer(commandArgs(trailingOnly = TRUE))
lines <- readLines(file("stdin"))
words <- tolower(unlist(strsplit(lines, "\\W+")))
counts <- sort(table(words), decreasing = TRUE)
counts_n <- counts[1:n]
cat(sprintf("%8d %s\n", counts_n, names(counts_n)), sep = "")
View promises.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RObject makeExplicit(SEXP prom) {
if (TYPEOF(prom) != PROMSXP) {
stop("Not a promise");
}
// recurse until we find the real promise, not a promise of a promise
View nice-xml.r
library(httr)
library(XML)
library(selectr)
xpath <- function(x) structure(x, class = "xpath")
sel <- function(x) xpath(css_to_xpath(x, prefix = "//"))
url <- "http://www.boxofficemojo.com/movies/?id=ateam.htm"
html <- content(GET(url), "parsed")