Skip to content

Instantly share code, notes, and snippets.

View hadley's full-sized avatar

Hadley Wickham hadley

View GitHub Profile
library(tidyverse)
library(gapminder)
gapminder
gapminder <- gapminder %>% mutate(year1950 = year - 1950)
# Nested data -------------------------------------------------------------
by_country <- gapminder %>%
group_by(continent, country) %>%
path <- "~/Documents/ingest/readxl/inst/extdata/datasets.xlsx"
zip_file <- function(path) {
stopifnot(file.exists(path))
path <- normalizePath(path)
contents <- utils::unzip(path, list = TRUE)
names(contents) <- c("path", "size", "date")
contents <- contents[contents$size > 0, , drop = FALSE]
only_if <- function(if_false, cond, if_true) {
if (cond) {
if_true
} else {
if_false
}
}
library(data.table)
dt <- data.table(x = 1:10)
bad_fun <- function(x) {
if (x > 5)
stop("Uhoh")
x * 10L
}
dt[, x := bad_fun(x), by = x]
dt
@hadley
hadley / subset2.cpp
Created November 4, 2015 16:29
An attempt a simpler subset2 implementation in C++
#include <Rcpp.h>
using namespace Rcpp;
inline SEXP subset_element(SEXP x, int i) {
size_t n = Rf_length(x);
if (i < 0 || i >= n || i == NA_INTEGER)
stop("Invalid subscript");
return VECTOR_ELT(x, i);
library(purrr)
library(github) # install_github("cscheid/rgithub")
library(dplyr)
library(stringr)
library(magrittr)
# Download issues ---------------------------------------------------------
ctx <- interactive.login("56b637a5baffac62cad9", "8e107541ae1791259e9987d544ca568633da2ebf")
issues1 <- get.repository.issues("hadley", "dplyr", per_page = 100)
msg <- function(..., prob = 0.25) {
if (runif(1) > prob) {
return(invisible())
}
messages <- c(...)
message(sample(messages, 1))
}
encourage <- function() {
diamonds <- ggplot2::diamonds
pryr::object_size(diamonds)
#> 3.46 MB

diamonds2 <- transform(diamonds, price_per_carat = price / carat)
pryr::object_size(diamonds2)
#> 3.89 MB

# Size of both data frames combined
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@hadley
hadley / beer.R
Last active September 10, 2015 16:49
bottles_of_beer <- function(i = 99) {
message("There are ", i, " bottles of beer on the wall, ", i, " bottles of beer.")
while(i > 0) {
tryCatch(
Sys.sleep(1),
interrupt = function(err) {
i <<- i - 1
if (i > 0) {
message(
"Take one down, pass it around, ", i,