Skip to content

Instantly share code, notes, and snippets.

View alexpghayes's full-sized avatar

alex hayes alexpghayes

View GitHub Profile
library(tidyverse)
library(stringr)
df <- tibble(x = map_chr(rpois(100, 5), ~paste(LETTERS[1:.x], collapse = ";")))
df
num_new_cols <- df$x %>%
str_count(pattern = "[A-Z]") %>% # you'll need to tweak pattern
max()
@alexpghayes
alexpghayes / facetted_residuals.R
Last active October 14, 2017 21:29
example of facetted residuals for Tian
library(tidyverse)
data(starwars)
df <- starwars %>%
select(mass, height, birth_year)
model <- lm(mass ~ height + birth_year, data = df)
# creates data like you have
library(tidyverse)
library(xkcd)
library(extrafont)
# see vignette("xkcd-info") on how to get the fonts approriately installed
font_import(pattern = "[X/x]kcd", prompt=FALSE)
loadfonts()
fonttable()
tibble(x = 0:7, y = rep(1, 8)) %>%
@alexpghayes
alexpghayes / hadley_load_dir_of_csvs.R
Created October 24, 2017 20:39
i fucking love the tidyverse
dir(annotation.path, full.names = TRUE) %>% map(read_csv, col_names = FALSE) %>% bind_rows()
@alexpghayes
alexpghayes / tibble_transpose.R
Created October 31, 2017 04:10
transposing tibbles, there's gotta be a better way
postr <- iris %>%
select(-Species)
postr %>%
t() %>%
as_tibble() %>%
transmute(param = colnames(postr),
samples = pmap(., c))
@alexpghayes
alexpghayes / t_df.R
Last active November 20, 2017 01:21
transpose a dataframe
library(tidyverse)
# Transpose a dataframe without accidentally converting everything to
# character. Assumes first column of input is a vector of feature names.
# If any of your data is non-numeric you're still SOL.
t_df <- function(data) {
vars <- pull(data, 1)
ids <- colnames(data)[-1]
library(dplyr)
library(rlang)
b <- c(2, 3)
x <- c("Sepal.Width", "Sepal.Length")
# define a function that does what we want to input like mult(c(2, 3), x1, x2), x1, x2 vector valued
mult <- function(x, ...) {
mat <- cbind(...)
@alexpghayes
alexpghayes / formulae_uuuuugh.R
Created January 18, 2018 23:29
jfc formulas (all hail recipes)
form <- mpg ~ splines::ns(hp, 2)
dat <- mtcars
mf <- model.frame(form, dat)
mt <- terms(mf)
head(model.matrix(mt, mf))
model.matrix(mt, head(mf))
# The following two commands remove any previously installed H2O packages for R.
if ("package:h2o" %in% search()) { detach("package:h2o", unload=TRUE) }
if ("h2o" %in% rownames(installed.packages())) { remove.packages("h2o") }
# Next, we download packages that H2O depends on.
pkgs <- c("statmod","RCurl","jsonlite")
for (pkg in pkgs) {
if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) }
}
@alexpghayes
alexpghayes / find_units.R
Created March 27, 2018 20:34
find the units of Z/15Z
f <- function(x) {
p <- x * (0:14) # take product
m <- p %% 15 # mod to stay in domain
print(paste("m =", x))
print(which(m == 1) - 1)
any(m == 1) # check if anything had an inverse
}
which(purrr::map_lgl(0:14, f)) - 1 # apply to all elements of Z / 15Z