1

我发现了一篇关于lavaan使用DiagrammeR. 但是,DiagrammeR这篇文章中使用的版本是版本0.6,我在尝试重现版本代码时遇到了一些麻烦0.8http://rich-iannone.github.io/DiagrammeR/docs.html)。

通过一些非常小的更改,代码如下所示

首先安装一个 SEMlavaan

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)

现在这是帖子中提出的代码

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)

到目前为止,一切都很好。

错误在这里

# 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)

在 的文档中,DiagrammeR据说“将函数重命名为graphviz_graph和”。graphviz_rendercreate_graphrender_graph

但是,进行此更改不起作用

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

知道为什么吗?

其他问题。在这篇文章中,这段代码似乎没有绘制残差协方差。知道如何用 绘制残差协方差DiagrammeR

谢谢

4

0 回答 0