Skip to content

Instantly share code, notes, and snippets.

View cbrown5's full-sized avatar
🦈

Chris Brown cbrown5

🦈
View GitHub Profile
@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))
#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 / 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")
@cbrown5
cbrown5 / gam-CIs.R
Last active February 12, 2025 16:37
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 / 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.