##################################################% -------- -----------
## Example with hidden variables
## Zhang (2008), Fig. 6, p.1882
##################################################
## create the DAG :
amat <- t(matrix(c(0,1,0,0,1, 0,0,1,0,0, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,1,0),5,5))
V <- LETTERS[1:5]
colnames(amat) <- rownames(amat) <- V
edL <- setNames(vector("list",length=5), V)
edL[[1]] <- list(edges= c(2,4),weights=c(1,1))
edL[[2]] <- list(edges= 3, weights=c(1))
edL[[3]] <- list(edges= 5, weights=c(1))
edL[[4]] <- list(edges= 5, weights=c(1))
## and leave edL[[ 5 ]] empty
g <- new("graphNEL", nodes=V, edgeL=edL, edgemode="directed")
if (require(Rgraphviz))
plot(g)
## define the latent variable
L <- 1
## compute the true covariance matrix of g
cov.mat <- trueCov(g)
## delete rows and columns belonging to latent variable L
true.cov <- cov.mat[-L,-L]
## transform covariance matrix into a correlation matrix
true.corr <- cov2cor(true.cov)
n <- 100000
alpha <- 0.01
p <- ncol(true.corr)
if (require("MASS")) {
## generate 100000 samples of DAG using standard normal error distribution
set.seed(289)
d.mat <- mvrnorm(n, mu = rep(0, p), Sigma = true.cov)
## estimate the skeleton of given data
suffStat <- list(C = cor(d.mat), n = n)
indepTest <- gaussCItest
resD <- skeleton(suffStat, indepTest, alpha = alpha, labels=colnames(true.corr))
## estimate all ordered unshielded triples
amat.resD <- as(resD@graph, "matrix")
print(u.t <- find.unsh.triple(amat.resD)) # four of them
## check and orient v-structures
vstrucs <- rfci.vStruc(suffStat, indepTest, alpha=alpha,
sepset = resD@sepset, g.amat = amat.resD,
unshTripl= u.t$unshTripl, unshVect = u.t$unshVect,
verbose = TRUE)
## Estimate the final skeleton and extend it into a PAG
## (using all 10 rules, as per default):
resP <- udag2apag(vstrucs$amat, suffStat, indepTest=indepTest, alpha=alpha,
sepset=vstrucs$sepset, verbose = TRUE)
print(Amat <- resP$graph)
} # only if "MASS" is there
Run the code above in your browser using DataLab