Skip to content

Instantly share code, notes, and snippets.

View timcdlucas's full-sized avatar

Tim Lucas timcdlucas

View GitHub Profile
library(dplyr)
library(glmnet)
library(splines)
library(tidyr)
library(ggplot2)
library(magrittr)
d <- data_frame(cov1 = rnorm(100),
cov2 = rnorm(100),
@timcdlucas
timcdlucas / gist:4e371eda4269910f2542d9e93b778f97
Created February 27, 2017 14:42
Violins vs bars with proportion data.
library(dplyr)
library(ggplot2)
d <- data.frame(x = rep(c('a', 'b'), 50), y = rbinom(100, 1, 0.4))
summary <- d %>%
group_by(x) %>%
summarise(prop = mean(y), CI = 0.95 * sqrt((sum(y)/50 * (50 - sum(y))/50) / 50))
df1 <- data.frame(y = rnorm(100), x = letters[1:2])
df2 <- data.frame(aggregate(. ~ x, df1, mean),
upperCI = aggregate(. ~ x, df1, function(x) quantile(x, 0.025))[, 2],
lowerCI = aggregate(. ~ x, df1, function(x) quantile(x, 0.975))[, 2])
ggplot() +
geom_violin(data = df1, aes(x = x, y = y)) +
geom_errorbar(data = df2, aes(x = x, ymax = upperCI, ymin = lowerCI), width = 0.5) +
geom_point(data = df2, aes(x, y))
d <- data.frame(year = rep(2012:2016, each = 30),
y = rnorm(5 * 30))
ggplot(d, aes(y = y)) +
geom_boxplot(aes(x = factor(year))) +
geom_smooth(aes(x = as.numeric(factor(year))))
@timcdlucas
timcdlucas / gist:cdb52b68c8c01968e438f9dc1871771d
Created October 4, 2016 09:01
Extract homogenous subsets from tukeyHSD object.
library(ggplot2)
library(igraph)
set.seed(1)
# Make some data
x <- data.frame(y = c(rnorm(200), rnorm(200, 3), rnorm(200, 6)),
x = rep(letters[1:20], each = 30))
@timcdlucas
timcdlucas / gist:d303b70eb3140c10bfc96cd24e3f7004
Created September 23, 2016 09:09
bivariate colour palette
# Code by Dave Redding
library(raster)
zzz=100
colsX<-raster(nrow=zzz,ncol=zzz)
values(colsX)<-1:ncell(colsX)
extent(colsX)<-c(-100,100,-100,100)
cols<-c("#00FF00","#FFFFFF")
x <- c(NA, 5:1)
y <- c(5:1, NA)
psum <- function(x, y){
x[is.na(x)] <- 0
y[is.na(y)] <- 0
x + y
}
@timcdlucas
timcdlucas / diffusion.R
Last active April 8, 2016 15:56
Diffusion based on direction and velocity raster
# Edit: whoops, radians
library(raster)
direction <- raster(nrows=100, ncols=100, xmn=0, xmx=10, , ymn=0, ymx=10)
values(direction) <- seq(0, 2 * pi, length.out = 100^2) + rnorm(100^2)
velocity <- raster(nrows=100, ncols=100, xmn=0, xmx=10, , ymn=0, ymx=10)
values(velocity) <- runif(100^2, 0, 0.1)
@timcdlucas
timcdlucas / gist:781a9c2d03eb144748fa
Created March 22, 2016 15:00
colourstrips in ggtree
t <- read.nexus('data/Chapter3/fritz2009geographical.tre')
tr1 <- t[[1]]
mat <- data.frame(name = tr1$tip.label)
mat$col1 = 'a'
mat$col1[1:300] <- 'b'
@timcdlucas
timcdlucas / DFT.R
Last active February 17, 2016 19:14
Discrete Fourier transform
# Simulate timeseries with period 10
time <- 1:200
y <- sin(time * 2 * pi / 10)
FT <- rep(NA, length(y) - 1)
for(k in 1:(length(y) - 1)){
FT[k] <- sum(y * (cos(-2 * pi * k * 0:(length(y) - 1) / length(y)) + 1i * sin(-2 * pi * k * 0:(length(y) - 1) / length(y))))