R/DSPC.R

Defines functions DSPC

Documented in DSPC

#' @title Distributed Sparse Principal Component Analysis
#' @description Performs distributed sparse principal component analysis (DSPC)
#' on a numeric dataset split across multiple nodes. Estimates sparse 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 gamma A numeric value specifying the sparsity parameter for SPC.
#' @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{Aspro}{List of sparse loading matrices for each node.}
#'   \item{Dspro}{List of diagonal residual variance matrices for each node.}
#'   \item{Sigmahatpro}{List of covariance matrices for each node.}
#' }
#'
#' @examples
#' set.seed(123)
#' data <- matrix(rnorm(500), nrow = 100, ncol = 5)
#' DSPC(data = data, m = 3, gamma = 0.03, n1 = 20, K = 5)
#' @export
DSPC <- function(data, m, gamma, n1, K) {
  n <- nrow(data)
  p <- ncol(data)
  
  Xpro <- scale(as.matrix(data))
  Sigmahatpro <- list()
  Aspro <- list()
  Dspro <- list()
  
  paras <- rep(gamma, m)
  
  for (i in 1:K) {
    idx <- sample(1:n, n1, replace = FALSE)
    Xsub <- scale(Xpro[idx, ])
    Sigmahat <- cor(Xsub)
    spc <- elasticnet::spca(Sigmahat, K = m, type = "Gram", sparse = "penalty", trace = FALSE, para = paras)
    V <- spc$loadings[, 1:m]
    eigvals <- eigen(Sigmahat)$values[1:m]
    As <- V %*% diag(sqrt(eigvals))
    h2 <- rowSums(As^2)
    Ds <- diag(diag(Sigmahat) - h2)
    Aspro[[i]] <- As
    Dspro[[i]] <- Ds
    Sigmahatpro[[i]] <- Sigmahat
  }
  
  return(list(Aspro = Aspro, Dspro = Dspro, Sigmahatpro = Sigmahatpro))
}

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.