movavgf | R Documentation |
The function returns a 2 column data frame with the first column named X. The second column named Y contains the smoothed dataset
movavgf(X, Y, bn, fn, f, val)
X |
The X vector of the 2D dataset |
Y |
The Y vector of the 2D dataset |
bn |
The no of elements before the current element that is needed to be included in the averaging window |
fn |
The no of elements after the current element that is needed to be included in the averaging window |
f |
This argument is a function using which the moving window used for averaging of the X, Y dataset is created. |
val |
The value around which the averaging window should be centered. |
Ensure before using that...
1) f_seq does not contain Inf elements.
2) f_seq does not contain NAs.
3) f_seq does not contain NANs.
All of the above will result in errors being thrown by the function.
The return type is always a 2 column data frame with the first column named X is same as the input argument X, while the second column Y is the smoothed dataset.
Chitran Ghosal
library(StatsChitran)
#build the dataset
set.seed(11)
X <- seq(-4, 4, by = 0.001)
Y <- X^2/16 + gauss(X, mu = 2, sig = 0.3, amp = 3, probability = F)
Y <- Y + rnorm(length(X), mean = 1, sd = 5)
##define the averaging function
lorentz <- function(v){
y <- 1/((v - 3)^2 + 5)
return(y)
}
##divide the plot into 4 co-ordinates
subplot(c(2,2))
##plot to check the averaging function
v <- seq(-10, 10, by=0.001)
plot(v, lorentz(v), type='l', col = 'red', main = 'averaging window', lwd=3)
#mark the position of the center value "val"
abline(v = 3)
##plot the dataset
plot(X, Y, col = rgb(0, 0.5, 0, 0.1), pch = 19, main = 'dataset vs averages')
#calculate the lorentz moving average
dat <- movavgf(X, Y, bn=300, fn=300, f=lorentz, val = 3)
#calculate the simple moving average (available in StatsChitran)
dat1 <- movavg(X, Y, bn=300, fn=300)
#plot the averages
lines(dat$X, dat$Y, col=rgb(1,0,0, 0.5), type='l', lwd = 3)
lines(dat1$X, dat1$Y, col=rgb(0,0,1, 0.25), type='l', lwd = 3)
#add legend
legend("topleft", legend = c("dataset", "lorentz MA", "MA"),
col = c(rgb(0, 0.5, 0, 0.5), rgb(1,0,0, 0.5), rgb(0,0,1, 0.25)), lwd = c(0, 3, 3), pch = c(19, NA, NA),
bty = "n")
##plot the averages only
plot(dat$X, dat$Y, col=rgb(1,0,0, 0.5), type='l', lwd = 3, main = 'moving averages')
lines(dat1$X, dat1$Y, col=rgb(0,0,1, 0.25), type='l', lwd = 3)
#add legend
legend("topleft", legend = c("lorentz MA", "MA"),
col = c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.25)), lwd = c( 3, 3), pch = c( NA, NA),
bty = "n")
##plot the errors
vec <- dat1$Y -dat$Y
plot(X, vec, type = 'l', col=rgb(0,1,1), main = 'absolute diff bw averages')
#add legend
legend("bottomleft", legend = "lorentz MA - MA",
col = rgb(0,1,1), lwd = 1, pch = NA,
bty = "n")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.