mrCoOccurNet: Generate a MrIML co-occurrence network

View source: R/mrCoOccurNet.R

mrCoOccurNetR Documentation

Generate a MrIML co-occurrence network

Description

This function generates a co-occurrence network from a provided list and calculates strength and directionality of the relationships. The output can be passed to igraph to plot a directed acyclic graph (DAG).

Usage

mrCoOccurNet(mrBootstrap_obj)

Arguments

mrBootstrap_obj

A list of bootstrapped partial dependencies output from mrBootstrap().

Value

A data frame representing the co-occurrence network with edge strengths and directionality.

Examples


library(tidymodels)
library(igraph)
library(ggnetwork)

data <- MRFcov::Bird.parasites
Y <- data %>%
  select(-scale.prop.zos) %>%
  dplyr::select(order(everything()))
X <- data %>%
  select(scale.prop.zos)

model_rf <- rand_forest(
  trees = 100, # 100 trees are set for brevity. Aim to start with 1000
  mode = "classification",
  mtry = tune(),
  min_n = tune()
) %>%
  set_engine("randomForest")

mrIML_rf <- mrIMLpredicts(
  X = X,
  Y = Y,
  X1 = Y,
  Model = model_rf,
  prop = 0.7,
  k = 5
)

mrIML_rf_boot <- mrIML_rf %>%
  mrBootstrap()

assoc_net_filtered <- mrIML_rf_boot %>%
  mrCoOccurNet_bootstrap() %>%
  filter(mean_strength > 0.05)

# Convert to igraph
g <- graph_from_data_frame(
  assoc_net_filtered,
  directed = TRUE,
  vertices = names(Y)
)
E(g)$Value <- assoc_net_filtered$mean_strength
E(g)$Color <- ifelse(
  assoc_net_filtered$direction == "negative",
  "blue", "red"
)
# Convert the igraph object to a ggplot object with NMDS layout
gg <- ggnetwork(g)
# Plot the graph
ggplot(
  gg,
  aes(x = x, y = y, xend = xend, yend = yend)
) +
  geom_edges(
    aes(color = Color, linewidth = Value),
    curvature = 0.2,
    arrow = arrow(length = unit(5, "pt"), type = "closed")
  ) +
  geom_nodes(
    color = "gray",
    size = degree(g, mode = "out") / 2
  ) +
  scale_color_identity() +
  theme_void() +
  theme(legend.position = "none") +
  geom_nodelabel_repel(
    aes(label = name),
    box.padding = unit(0.5, "lines"),
    size = 2,
    segment.colour = "black",
    colour = "white",
    fill = "grey36"
  )


nfj1380/mrIML documentation built on June 2, 2025, 1:03 a.m.