1

I found a really great post about converting lavaan output using DiagrammeR. However, the version of DiagrammeR used in this post is version 0.6 and I am running into some troubles in trying to reproduce the code for version 0.8 (http://rich-iannone.github.io/DiagrammeR/docs.html).

With some very minor changes, the code goes like this

First fit a SEM with lavaan

library("stringr")
library("lavaan")
library("DiagrammeR")
library("dplyr")
library("semPlot")

 model <- '
 # latent variables
 ind60 =~ x1 + x2 + x3
 dem60 =~ y1 + y2 + y3 + y4
 dem65 =~ y5 + y6 + y7 + y8
 # regressions
 dem60 ~ ind60
 dem65 ~ ind60 + dem60
 # residual covariances
  y1 ~~ y5
  y2 ~~ y4 + y6
  y3 ~~ y7
  y4 ~~ y8
  y6 ~~ y8
'

fit <- growth(model, data = PoliticalDemocracy)

semPaths(fit, intercept = FALSE, whatLabel = "est",
         residuals = FALSE, exoCov = FALSE)

Now this is the code proposed in the post

paths <- fit %>%
  parameterestimates %>%
  select(lhs, op, rhs, est)

# Latent variables are left-hand side of "=~" lines
latent <- paths %>%
  filter(op == "=~") %>%
  select(nodes = lhs) %>%
  distinct %>%
  mutate(shape = "circle")

# Manifest variables are not latent variables
`%not_in%` <- Negate(`%in%`)
manifest <- paths %>%
  filter(op != "~1", lhs %not_in% latent$nodes) %>%
  select(nodes = lhs) %>%
  distinct %>%
  mutate(shape = "square")

# Nodes are prepared
node_set <- combine_ndfs(latent, manifest)

# Edges will be labeled by the parameter estimates
all_paths <- paths %>%
  filter(op != "~1") %>%
  mutate(label = round(est, 2)) %>%
  select(-est)

# Factor loadings are the paths in the "=~" lines
loadings <- all_paths %>%
  filter(op == "=~") %>%
  mutate(edge_from = lhs, edge_to = rhs, style = "dashed") %>%
  select(edge_from, edge_to, style, label)

regressions <- all_paths %>%
  filter(op == "~") %>%
  rename(edge_to = lhs, edge_from = rhs) %>%
  mutate(style = "solid") %>%
  select(edge_from, edge_to, style, label)

edge_set <- combine_edfs(loadings, regressions)

So far, so good.

The errors come here

# Combine edges and nodes
my_graph <- graphviz_graph(
  nodes = node_set,
  edges_df = edge_set,
  graph_attrs = c("ranksep = 1"))

# We can plot the graph directly
graphviz_render(my_graph)

In the doc of DiagrammeR, it is said that "renamed functions graphviz_graph and graphviz_render to create_graph and render_graph".

However, making this change does not work

my_graph <- create_graph(
  nodes = node_set,
  edges_df = edge_set,
  graph_attrs = c("ranksep = 1"))

Any idea why?

Other question. In this post, this code does not seem to plot the residual co-variances. Any idea how to plot residual co-variances with DiagrammeR?

Thank you

MYaseen208
  • 22,666
  • 37
  • 165
  • 309
giac
  • 4,261
  • 5
  • 30
  • 59

0 Answers0