# Need to install the metaSEM packages first # The script "GLS_functions.R" with the functions compacov() and compacov_meanr() has to be in the working directory. require(metaSEM) source("GLS_functions.R") # example data from metaSEM package data <- Digman97$data # list of correlation matrices n <- Digman97$n # vector with sample sizes nvar <- 5 # number of variables of interest ####### general code ncor <- nvar*(nvar-1)/2 r <- t(sapply(data,vechs)) present <- (is.na(r)==FALSE)/1 rlabels <- vechs(outer(1:nvar, 1:nvar, function(x, y) paste("v",x,"v", y, sep = ""))) # create filter matrices Id <- diag(1,ncor) createX <- function(present){t(Id[present==TRUE,])} d <- apply(present,1,createX) X <- matrix(unlist(d),nrow=sum(present),ncol=ncor,byrow=TRUE) # vector of present correlations rvec <- c(t(r)) rvec <- rvec[is.na(rvec)==FALSE] # vector of present correlations rvec <- c(t(r[is.na(r)==FALSE])) # V matrices m <- mapply(compacov,data,n=n) Vi <- list() for (i in 1:ncol(m)){d <- matrix(m[,i],ncor,ncor) Vi[[i]] <- d[present[i,]==1,present[i,]==1]} V <- bdiagMat(Vi) # calculate means and acov means_GLS_fixed <- solve(t(X)%*%solve(V)%*%X)%*%t(X)%*%solve(V)%*%rvec acov_GLS_fixed <- solve(t(X)%*%solve(V)%*%X) dimnames(means_GLS_fixed) <- list(rlabels,"pooledR") dimnames(acov_GLS_fixed) <- list(rlabels,rlabels) # V matrices calculated with mean correlations (Becker & Fahrbach (1994)) Vi <- compacov_meanr(data,n) # remove missing correlations from Vi's for (i in 1:length(Vi)){ Vi[[i]] <- Vi[[i]][present[i,]==1,present[i,]==1]} V <- bdiagMat(Vi) # calculate mean correlations and acov means_GLS_fixed_2 <- solve(t(X)%*%solve(V)%*%X)%*%t(X)%*%solve(V)%*%rvec acov_GLS_fixed_2 <- solve(t(X)%*%solve(V)%*%X) dimnames(means_GLS_fixed_2) <- list(rlabels,"pooledR") dimnames(acov_GLS_fixed_2) <- list(rlabels,rlabels) ##### Results means_GLS_fixed acov_GLS_fixed means_GLS_fixed_2 acov_GLS_fixed_2