R/av.R

Defines functions av

Documented in av

#' Compute the columnwise average of a collection of vectors.
#'
#' A function that computes \eqn{|\mathbb{S}_j|^{-1} \sum_{S \in \mathbb{S}_j} x_{S,j}}
#' for a collection of vectors \eqn{x_{\mathbb{S}}} over the missingness patterns. 
#' This is defined in Step 3 of Algorithms 2 and 3 in \insertCite{BB2024;textual}{MCARtest}.
#'
#' @param patterns The collection of missingness patterns.
#' @param x_S The collection of vectors over missingness patterns.
#'
#' @references \insertRef{BB2024}{MCARtest}
#'
#' @return The vector of entry \eqn{|\mathbb{S}_j|^{-1} \sum_{S \in \mathbb{S}_j} x_{S,j}}.
#' @export
#'
#' @examples
#' library(MASS)
#'
#' d = 3
#' n = 200
#' SigmaS=list() #Random 2x2 correlation matrices (necessarily consistent)
#' for(j in 1:d){
#' x=runif(2,min=-1,max=1); y=runif(2,min=-1,max=1); SigmaS[[j]]=cov2cor(x%*%t(x) + y%*%t(y))
#' }
#'
#' X = data.frame(matrix(nrow = 3*n, ncol = 3))
#' X[1:n, c(1,2)] = mvrnorm(n, c(0,0), SigmaS[[1]])
#' X[(n+1):(2*n), c(2, 3)] = mvrnorm(n, c(0,0), SigmaS[[2]])
#' X[(2*n+1):(3*n), c(1, 3)] = mvrnorm(n, c(0,0), SigmaS[[3]])
#' X = as.matrix(X)
#'
#' tmp = get_SigmaS(X)
#' av(tmp$mu_S, tmp$patterns)


av = function(x_S, patterns){
  n_pattern = length(patterns)
  d = max(unlist(patterns))
  
  res = numeric(length = d)
  for (j in 1:d){
    num = 0
    den = 0
    for (i in 1:n_pattern){
      if (j %in% patterns[[i]]){
        num = num + x_S[[i]][which(patterns[[i]] == j)[[1]]]
        den = den + 1
      }
    }
    
    res[j] = num/den
  }
  
  return(res)
}

Try the MCARtest package in your browser

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

MCARtest documentation built on June 26, 2025, 5:08 p.m.