Skip to content

Instantly share code, notes, and snippets.

View jarad's full-sized avatar

Jarad Niemi jarad

View GitHub Profile
@jarad
jarad / read_my_dir.R
Last active May 30, 2023 15:49
Function to read a directory worth of data
# From https://gist.github.com/jarad/8f3b79b33489828ab8244e82a4a0c5b3
library("dplyr")
library("tidyr")
library("readr")
read_my_csv = function(f, into) {
readr::read_csv(f) %>%
dplyr::mutate(file = f) %>%
tidyr::separate(file, into)
@jarad
jarad / read_dir_with_drake.R
Last active May 31, 2020 16:26
Script to read a directory of data similar to `read_dir` but using drake to remember what has already been read.
library("drake")
files = list.files("data", "*.csv", full.names = TRUE)
add2 = function(d) { # example function to apply to each individual data.frame
d$x = d$x+2
return(d)
}
plan = drake_plan(
@jarad
jarad / frontmatter.tex
Last active December 13, 2018 16:41
Beamer template for approximate Iowa State University colors and my preferred style
\documentclass{beamer}
\usetheme{AnnArbor}
\usecolortheme{beaver}
\usefonttheme[onlymath]{serif} % uncomment for article style math
\setlength{\unitlength}{\textwidth} % measure in textwidths
\usepackage[normalem]{ulem}
@jarad
jarad / install_and_load_packages
Created October 14, 2014 19:59
Function to install (if necessary) and load R packages
# From http://stackoverflow.com/questions/4090169/elegant-way-to-check-for-missing-packages-and-install-them
install_and_load_packages <- function(x){
for( i in x ){
# require returns TRUE invisibly if it was able to load package
if( ! require( i , character.only = TRUE ) ){
# If package was not able to be loaded then re-install
install.packages( i , dependencies = TRUE )
# Load package after installing
require( i , character.only = TRUE )
}
@jarad
jarad / Vectorize_script.R
Created April 5, 2016 19:14
Example usage of the Vectorize() function in R for evaluation of a likelihood surface for multiple values of the parameter
y = rnorm(5)
log_like = function(theta, y) {
sum(dnorm(y,theta,log=TRUE))
}
thetas = c(1,2)
# Evaluating the theta vector one at a time works,
log_like(thetas[1],y)
@jarad
jarad / convergenceToADistribution.R
Created December 15, 2011 21:28
random walk Metropolis for a equal mixture of two normals
mn = 3
f = function(x) {
n = length(x)
apply(.5*cbind(dnorm(x,-mn),dnorm(x,mn)),1,sum)
}
# Random-walk Metropolis
set.seed(1)
n.reps = 1e5
x.reps = rep(NA,n.reps)