Skip to content

Instantly share code, notes, and snippets.

@chrishanretty
Created March 20, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrishanretty/0313427865568db8d44634e8dbd3abf8 to your computer and use it in GitHub Desktop.
Save chrishanretty/0313427865568db8d44634e8dbd3abf8 to your computer and use it in GitHub Desktop.
Smoothing and piecewise linear data-generating processes
### Let's generate some data with a step function
library(mgcv)
set.seed(1116)
nDays <- 200
day <- 1:nDays
y <- rnorm(200, 1, 0.25) + I(day > 100) * -0.5
y <- ifelse(y < 0,
0,
y)
dat <- data.frame(y = y,
day = day,
npi = day > 100)
png(file = "smooth1.png")
plot(day, y,
xlab = "Day",
ylab = "Value",
pch = 19)
abline(v = 100, col = "darkgrey")
dev.off()
piecewise <- lm(y ~ 1 + npi, data = dat)
png(file = "smooth2.png")
plot(day, y,
xlab = "Day",
ylab = "Value",
pch = 19)
abline(v = 100, col = "darkgrey")
yhat <- predict(piecewise)
lines(day, yhat)
dev.off()
smoothed <- gam(y ~ s(day), data = dat)
yhat2 <- predict(smoothed)
png(file = "smooth3.png")
plot(day, y,
xlab = "Day",
ylab = "Value",
pch = 19)
abline(v = 100, col = "darkgrey")
yhat <- predict(piecewise)
lines(day, yhat2)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment