R/DPC.R

Defines functions DPC

Documented in DPC

#' @title Distributed Principal Component Analysis
#' @description Performs distributed principal component analysis on a numeric dataset
#' split across multiple nodes. Estimates loading matrices, residual variances, and
#' covariance matrices for each node.
#'
#' @param data A numeric matrix containing the total dataset.
#' @param m An integer specifying the number of principal components.
#' @param n1 An integer specifying the length of each data subset.
#' @param K An integer specifying the number of nodes.
#'
#' @return A list with the following components:
#' \describe{
#'   \item{Ahat}{List of estimated loading matrices for each node.}
#'   \item{Dhat}{List of diagonal residual variance matrices for each node.}
#'   \item{Sigmahat}{List of covariance matrices for each node.}
#' }
#'
#' @examples
#' set.seed(123)
#' data <- matrix(rnorm(500), nrow = 100, ncol = 5)
#' DPC(data = data, m = 3, n1 = 20, K = 5)
#'
#' @export
DPC <- function(data, m, n1, K) {
  n <- nrow(data)
  p <- ncol(data)
  Sigmahat <- list()
  Ahat <- list()
  Dhat <- list()
  
  for (i in 1:K) {
    L <- matrix(rep(0, K * n1), ncol = n1)
    R <- matrix(0, n1, n)
    L[i, ] <- sample(1:n, n1, replace = FALSE)
    r <- matrix(c(1:n1, L[i, ]), ncol = n1, byrow = TRUE)
    R[t(r)] <- 1
    X1 <- R %*% as.matrix(data)
    X <- scale(X1)
    
    Sigmahat[[i]] <- cor(X)
    eig <- eigen(Sigmahat[[i]])
    lambdahat <- eig$values[1:m]
    ind <- order(lambdahat, decreasing = TRUE)
    lambdahat <- lambdahat[ind]
    Q <- eig$vectors[, ind]
    Qhat <- Q[, 1:m]
    
    Ahat1 <- matrix(0, nrow = p, ncol = m)
    for (j in 1:m) {
      Ahat1[, j] <- sqrt(lambdahat[j]) * Qhat[, j]
    }
    Ahat[[i]] <- Ahat1
    
    h0 <- diag(Ahat[[i]] %*% t(Ahat[[i]]))
    Dhat[[i]] <- diag(Sigmahat[[i]] - h0)
  }
  
  return(list(Ahat = Ahat, Dhat = Dhat, Sigmahat = Sigmahat))
}

Try the DSFM package in your browser

Any scripts or data that you put into this service are public.

DSFM documentation built on Dec. 1, 2025, 5:09 p.m.