This is the code used in the slides for the Workshop ‘Applying Network Analysis to Psychological Data’ at the EFPSA Congress 2016. The slides can be downloaded here http://jmbh.github.io.
# load necessary pacakges
library(devtools)
#install_github('SachaEpskamp/qgraph')
#install_github('jmbh/mgm')
library(qgraph)
library(mgm)
library(httr) # downloading data from https
# construct a network
AdjacencyMatrix <- matrix(0,4,4)
AdjacencyMatrix[1,2] <- AdjacencyMatrix[2,1] <- 1
AdjacencyMatrix[2,3] <- AdjacencyMatrix[3,2] <- 1
AdjacencyMatrix[2,4] <- AdjacencyMatrix[4,2] <- 1
AdjacencyMatrix
## [,1] [,2] [,3] [,4]
## [1,] 0 1 0 0
## [2,] 1 0 1 1
## [3,] 0 1 0 0
## [4,] 0 1 0 0
qgraph(AdjacencyMatrix) # visualize
## set up random network
p <- 20 # number of nodes
AdjMatrix <- matrix(0,p,p) #create empty matrix
set.seed(22) #set seed for reproducibility
AdjMatrix[upper.tri(AdjMatrix)] <- sample(0:1,(p*(p-1))/2,
prob=c(.9,.1),replace=TRUE)
AdjMatrix <- AdjMatrix + t(AdjMatrix) # make symmetric
AdjMatrix[1:5,1:5] # look at edges between first 5 nodes
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0 0 0 0 0
## [2,] 0 0 1 0 0
## [3,] 0 1 0 0 0
## [4,] 0 0 0 0 0
## [5,] 0 0 0 0 0
qgraph(AdjMatrix) # visualize
url='https://jmbh.github.io/figs/efpsa_workshop/BDIdata.RDS'
GET(url, write_disk("BDIdata.RDS", overwrite=TRUE))
## Response [https://jmbh.github.io/figs/efpsa_workshop/BDIdata.RDS]
## Date: 2016-05-14 09:14
## Status: 200
## Content-Type: application/octet-stream
## Size: 34.3 kB
## <ON DISK> C:\Users\jo\Dropbox\MyData\_PhD\_Talks\efpsa_congress_2016\na_workshop\BDIdata.RDS
BDI_data <- readRDS('BDIdata.RDS')
# look at data
# data
BDI_data$data[1:3,1:5]
## aids01 aids02 aids03 aids04 aids05
## [1,] 1 3 1 2 1
## [2,] 3 4 2 1 1
## [3,] 1 1 1 2 1
#labels
BDI_data$vnames[1:5]
## [1] "Falling Asleep" "Sleep During the Night"
## [3] "Waking Up Too Early" "Sleeping Too Much"
## [5] "Feeling Sad"
CorMatrix <- cor(BDI_data$data)
round(CorMatrix[1:4, 1:4],2)
## aids01 aids02 aids03 aids04
## aids01 1.00 0.28 0.22 0.02
## aids02 0.28 1.00 0.34 -0.06
## aids03 0.22 0.34 1.00 -0.10
## aids04 0.02 -0.06 -0.10 1.00
# visualization: ring layout
qgraph(CorMatrix, nodeNames=BDI_data$vnames, legend.cex = .3, vsize=4)
# visualization: 'spring' layout (Fruchterman Reingold algorithm)
qgraph(CorMatrix, nodeNames=BDI_data$vnames,
legend.cex = .3, layout='spring', vsize=3)
## BDI Data
# fit conditional independence network
fit <- mgmfit(BDI_data$data, rep('g', 28), rep(1, 28), d=2, pbar = FALSE)
round(fit$wadj[1:4, 1:4],2)
## [,1] [,2] [,3] [,4]
## [1,] 0.00 0.13 0.03 0.00
## [2,] 0.13 0.00 0.22 0.00
## [3,] 0.03 0.22 0.00 0.05
## [4,] 0.00 0.00 0.05 0.00
qgraph(fit$wadj, nodeNames=BDI_data$vnames,
legend.cex = .3, layout='spring', vsize=3)