what I love about R
Apr. 4th, 2012 11:36 pmOne thing I really love about R is how I can write improperly-scoped code, and everything still works.

----
This is much cleaner:

Note how the Exponential Moving Average (in blue) is backward-looking, and less smooth than the Gaussian one (in red), even though these kernels, when viewed as distributions, have the same standard deviation of 3.
I think that this is in part due to the Exponential kernel not being as smooth as the Gaussian one, but I also suspect that it weights the points less evenly.
gSmooth <- function(x,y, kernelSd=1, kernel=function(z) dnorm(z,mean=x[i],sd=kernelSd)){
v <- c()
for (i in seq_len(length(x))){
weights <- sapply(x, kernel)
v[i] <- sum(weights*y)/sum(weights)
}
list(x=x,y=v)
}
plot(data$ZQ, type="l", ylim=c(0,130))
ss <- gSmooth(1:n,data$ZQ)
pplot(ss$x, ss$y, type="l", col="red")
ss <- gSmooth(1:n,data$ZQ, kernelSd=3)
pplot(ss$x, ss$y, type="l", col="blue")

----
This is much cleaner:
gSmooth <- function(x,y, kernel=gaussKernel){
v <- c()
for (i in seq_len(length(x))){
center <- x[i]
weights <- sapply(x, function(z) kernel(z, center))
v[i] <- sum(weights*y)/sum(weights)
}
list(x=x,y=v)
}
gaussKernel <- function(z, center) dnorm(z, mean=center, sd=kernelSd)
emaKernel <- function(z, center) if(z<=center) return(exp((z-center)/kernelSd))
else return(0) ## Exponential Moving Average
plot(data$dayNumber, data$ZQ, type="p")
pplot(data$dayNumber, data$ZQ, type="l")
kernelSd <- 3
ss <- gSmooth(data$dayNumber,data$ZQ)
pplot(ss$x,ss$y, type="l", col="red")
kernelSd <- 3
ss <- gSmooth(data$dayNumber,data$ZQ, kernel=emaKernel)
pplot(ss$x,ss$y, type="l", col="blue")

Note how the Exponential Moving Average (in blue) is backward-looking, and less smooth than the Gaussian one (in red), even though these kernels, when viewed as distributions, have the same standard deviation of 3.
I think that this is in part due to the Exponential kernel not being as smooth as the Gaussian one, but I also suspect that it weights the points less evenly.