##################################################
## Example with hidden variables
## Zhang (2008), Fig. 6, p.1882
##################################################
## draw a DAG with latent variables
## this example is taken from Zhang (2008), Fig. 6, p.1882 (see references)
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 <- as.character(1:5)
colnames(amat) <- rownames(amat) <- V
edL <- vector("list",length=5)
names(edL) <- 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))
g <- new("graphNEL", nodes=V, edgeL=edL,edgemode="directed")
if(require("Rgraphviz")) plot(g) else print(g)
## define the latent variable
L <- 1
## compute the true covariance matrix of g
cov.mat <- trueCov(g)
## delete rows and columns which belong to L
true.cov <- cov.mat[-L,-L]
## transform it in a correlation matrix
true.corr <- cov2cor(true.cov)
if (require("MASS")) {
## generate 100000 samples of DAG using standard normal error distribution
n <- 100000
alpha <- 0.01
set.seed(314)
d.mat <- mvrnorm(n, mu = rep(0,dim(true.corr)[1]), Sigma = true.cov)
## estimate the skeleton of given data
suffStat <- list(C = cor(d.mat), n = n)
indepTest <- gaussCItest
resD <- skeleton(suffStat, indepTest, p=dim(true.corr)[2], alpha = alpha)
## estimate v-structures conservatively
tmp <- pc.cons.intern(resD, suffStat, indepTest, alpha, version.unf = c(1, 1))
## tripleList <- tmp$unfTripl
resD <- tmp$sk
## estimate the final skeleton of given data using Possible-D-Sep
pdsepRes <- pdsep(resD@graph, suffStat, indepTest, p=dim(true.corr)[2],
resD@sepset, alpha = alpha, m.max = Inf,
pMax = resD@pMax)
## extend the skeleton into a PAG using all 10 rules
resP <- udag2pag(pag = pdsepRes$G, pdsepRes$sepset, rules = rep(TRUE,10),
verbose = TRUE)
colnames(resP) <- rownames(resP) <- as.character(2:5)
print(resP)
} # only if "MASS" is there
Run the code above in your browser using DataLab