data(Bowley)
# plot the data
with(Bowley,plot(Year, Value, type='b', lwd=2,
ylab="Value of British and Irish Exports",
main="Bowley's example of the method of smoothing curves"))
# find moving averages
# simpler version using stats::filter
running <- function(x, width = 5){
as.vector(stats::filter(x, rep(1 / width, width), sides = 2))
}
mav3<-running(Bowley$Value, width=3)
mav5<-running(Bowley$Value, width=5)
mav9<-running(Bowley$Value, width=9)
lines(Bowley$Year, mav3, col='blue', lty=2)
lines(Bowley$Year, mav5, col='green3', lty=3)
lines(Bowley$Year, mav9, col='brown', lty=4)
# add lowess smooth
lines(lowess(Bowley), col='red', lwd=2)
# Initial version, using ggplot
library(ggplot2)
ggplot(aes(x=Year, y=Value), data=Bowley) +
geom_point() +
geom_smooth(method="loess", formula=y~x)
Run the code above in your browser using DataLab