Skip to content

Instantly share code, notes, and snippets.

View cbrown5's full-sized avatar
🦈

Chris Brown cbrown5

🦈
View GitHub Profile
@cbrown5
cbrown5 / rw2sim.R
Last active March 25, 2024 20:43
Simulate from a random walk order 2 model
#Simulate from an RW2 (random walk order 2) model.
# Useful for generating predictions from INLA RW2 models.
# When forecast, RW2 models predict continuation of trend, with
# deviations from the trend controlled by the sd parameter.
#
# See: https://inla.r-inla-download.org/r-inla.org/doc/latent/rw2.pdf
# Can intialize the RW2 at a given starting point, this needs
# needs to be two consecutive points, given we are working with
# second order differences.
@cbrown5
cbrown5 / gam-CIs.R
Last active May 7, 2024 11:27
Simplified simulation of credible intervals (empirical bayes) in mgcv
#Functions to simulate predictions and CIs from a GAM
# CJ Brown
# 2023-03-24
#
# based on code in ?gam.predict and Wood, S.N. (2017) Generalized Additive Models: An
# Introduction with R (2nd edition). Chapman and
# Hall/CRC.
library(lazyeval)
@cbrown5
cbrown5 / gam_bayes_predict.R
Created August 22, 2021 23:24
GAM predictions using empirical bayes - function template
# Template for doing empirical Bayes prediction from a GAM with mgcv
# CJ Brown 2021-08-23
#
# See Wood 2017 and ?predict.gam for more info
#First of all its often easiest to create your prediction dataframe with
# visreg, e.g. this makes a df across all values of NEOLI_Total
# and "has_fee":
xfit <- visreg(tour_mod, xvar = "NEOLI_Total", partial = FALSE,
plot = FALSE, by = "has_fee")
#Demonstration of splines in R
#Can be used to add nonlinearity to linear models (e.g. GLMs)
library(splines)
x <- rnorm(10000)
n_df <- 5
ns_design_mat <- ns(x, n_df) #n_df degrees of freedom
plot(x, ns_design_mat[,1], ylim = c(-1, 1))
points(x, ns_design_mat[,2], col = "red")
points(x, ns_design_mat[,3], col = "blue")
@cbrown5
cbrown5 / scale-numerics-data-frame.R
Created August 4, 2021 10:33
scale numeric variables in a data.frame
#Apply scale to just numeric variables
#keep all variables
dat2 <- dat %>%
mutate(across(where(is.numeric), scale))
#keep just numerical variables, drop the others from the data.frame
dat2 <- dat %>%
transmute(across(where(is.numeric), scale))
@cbrown5
cbrown5 / dist_from_cluster_membership.R
Created March 10, 2021 03:22
Turn a dataframe that indicates what cluster each sample belongs to into a distance matrix
#Function that converts dataframe of cluster identities
# to distance matrix representation of clusters (where rows/cols are samples/IDs and
# 0 indicates that pair are not in same cluster, 1 indicates they are in same cluster
as_dist_mat <- function(dtemp){
# dtemp is dataframe with two columns:
#ID is a unique cell ID
#Cluster is a variable giving cluster a cell belongs to
#It should be arranged so we are certain
#cells are in ascending order
@cbrown5
cbrown5 / gamma_mode_sd.R
Created February 16, 2021 23:07
Parameterize gamma distribution with mode and SD
#Parameterize gamma distribution with mode and SD
#Choose summary stats for the gamma
xmode <- 1 #mode of distribution
xsd <- 0.5 # SD
#Calculate gamma parameters
beta <- (xmode + sqrt(xmode^2 + 4*xsd^2 ) ) / ( 2 * xsd^2 )
alpha <- 1 + xmode * beta
# Why you should plot data before doing statistical tests
# CJ Brown 2020-11-06
#More at www.conservationhackers.org
library(ggplot2)
#
# Make some data
#
n <- 50 #Sample size per group
# How to ggplot2 efficiently
# CJ Brown 2020-10-27
library(ggplot2)
#
# Make some data
#
n <- 20 #Sample size per group
@cbrown5
cbrown5 / st_as_raster
Created May 18, 2020 12:18
Convert stars raster to raster::raster
#Takes as an input a stars raster layer
#CJ Brown 2020-05-18
st_as_raster <- function(rstars){
rext <- st_bbox(rstars)
raster(t(rstars[[1]]), xmn = rext[1], xmx = rext[3],
ymn = rext[2], ymx=rext[4],
crs = st_crs(rstars)$proj4string)
}