## --------------------------------------------------------------------------------------- x <- 1:10 x diff(x) cumsum(x) # Not so nice in the ends! cumsum(diff(x)) diff(cumsum(x)) # Put a zero in beginning to fix it cumsum(diff(c(0,x))) diff(cumsum(c(0,x))) ## --------------------------------------------------------------------------------------- lagvec <- function(x, lag){ if (lag > 0) { ## Lag x, i.e. delay x lag steps return(c(rep(NA, lag), x[1:(length(x) - lag)])) }else if(lag < 0) { ## Lag x, i.e. delay x lag steps return(c(x[(abs(lag) + 1):length(x)], rep(NA, abs(lag)))) }else{ ## lag = 0, return x return(x) } } ## --------------------------------------------------------------------------------------- lagdf <- function(x, lag) { # Lag x, i.e. delay x lag steps if (lag > 0) { x[(lag+1):nrow(x), ] <- x[1:(nrow(x)-lag), ] x[1:lag, ] <- NA }else if(lag < 0) { # Lag x "ahead in time" x[1:(nrow(x)-abs(lag)), ] <- x[(abs(lag)+1):nrow(x), ] x[(nrow(x)-abs(lag)+1):nrow(x), ] <- NA } return(x) } ## ----out.width="0.4\\textwidth", fig.width=2*figwidth----------------------------------- par(mfrow=c(1,2)) # Generate realizations n <- 100 x1 <- filter(rnorm(n), 0.9, "recursive") plot(x1, type="b", ylim=c(-6,6)) x2 <- filter(rnorm(n), 0.9, "recursive") lines(x2, type="b", col=2) x3 <- filter(rnorm(n), 0.9, "recursive") lines(x3, type="b", col=3) # Generate 1000 realizations X <- matrix(filter(rnorm(1000*n), 0.9, "recursive"), nrow=n) # One realization (i.e. a time series) X[ ,1] # Realization of the stochastic variable at one time point hist(X[50, ]) ## ----out.width="0.4\\textwidth"--------------------------------------------------------- # Simulate a process n <- 100 x <- filter(rnorm(n), 0.9, "recursive") plot(x) # The acf and "height" of "lag 1 bar" val <- acf(x) val[1] # The correlation with lag 1 cor(x, lagvec(x,1), use="complete.obs") ## ----echo=FALSE, fig.height=figheight, fig.width=figwidth, out.width="0.6\\textwidth"---- # ACF of white noise set.seed(8372) x <- rnorm(1000) acf(x) ## ----eval=FALSE------------------------------------------------------------------------- ## x <- readline("Write a sequence of numbers from 0 to 9\n") ## x <- as.numeric(strsplit(x,"")[[1]]) ## acf(x) ## ----size="tiny", fig.width=2*figwidth, out.width="0.7\\textwidth"---------------------- ######## # ACF of a sine w <- 10 x <- sin((1:1000)*2*pi*(w/1000)) ## ----size="tiny", fig.width=2*figwidth, out.width="0.7\\textwidth"---------------------- # Plot it par(mfrow=c(1,2)) plot(x) # The ACF is actually also a sine! acf(x, lag.max=500) # Can you "screw it" and make it look like white noise up by altering a single value in x? #x[100] <- ?? #acf(x, lag.max=500)