if (FALSE) {
# Data generation
n <- 400 # number of units
d <- 10000 # number of variables
n0 <- 200 # initial sample
q <- 20 # required number of PCs
x <- matrix(rnorm(n*d,sd=1/sqrt(d)),n,d) # data matrix
x <- t(apply(x,1,cumsum)) # standard Brownian motion
# Initial PCA
# Initial PCA
xbar0 <- colMeans(x[1:n0,])
pca0 <- batchpca(x0c, q, center=xbar0, byrow=TRUE)
# Incremental PCA with rotation
xbar <- xbar0
pca1 <- pca0
system.time({
for (i in n0:(n-1)) {
xbar <- updateMean(xbar, x[i+1,], i)
pca1 <- incRpca(pca1$values, pca1$vectors, x[i+1,], i, center=xbar)
}
})
# Incremental PCA without rotation
xbar <- xbar0
pca2 <- list(values=pca0$values, Ut=pca0$vectors, Us=diag(q))
system.time({
for (i in n0:(n-1)) {
xbar <- updateMean(xbar, x[i+1,], i)
pca2 <- incRpca.rc(pca2$values, pca2$Ut, pca2$Us, x[i+1,],
i, center = xbar)
# Rotate the PC basis and reduce its size to q every k observations
if (i %% q == 0 || i == n-1)
{ pca2$values <- pca2$values[1:q]
pca2$Ut <- pca2$Ut %*% pca2$Us[,1:q]
pca2$Us <- diag(q)
}
}
})
# Check that the results are identical
# Relative differences in eigenvalues
range(pca1$values/pca2$values-1)
# Cosines of angles between eigenvectors
abs(colSums(pca1$vectors * pca2$Ut))
}
Run the code above in your browser using DataLab