Created
March 20, 2021 11:33
-
-
Save chrishanretty/0313427865568db8d44634e8dbd3abf8 to your computer and use it in GitHub Desktop.
Smoothing and piecewise linear data-generating processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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