forked from bioinformatics-leibniz-hki/correlation-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
726 lines (562 loc) · 23.8 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
---
title: "Correlation workshop"
subtitle: "Micom 2021"
author: "Daniel Loos"
date: "`r {date()}`"
bibliography: src/literature.bib
link-citations: yes
output:
html_document:
css: src/report.css
dev: png
toc: true
toc_depth: 4
toc_float: true
theme: united
df_print: kable
---
```{r setup, echo = FALSE, warning = FALSE, include=FALSE}
knitr::opts_chunk$set(
fig.width = 15,
fig.height = 10,
# show output
echo = TRUE,
warning = FALSE,
message = FALSE,
error = TRUE, # do not stop on error and show error message instead
cache = TRUE,
comment = ""
)
knitr::opts_knit$set(
root.dir = here::here()
)
setwd(here::here())
source("src/setup.R")
```
This is an informal and hopefully intuitive way to teach the nature of correlations.
Please consider textbooks and review-articles for detailed study.
This project can be downloaded from [GitHub](https://github.com/bioinformatics-leibniz-hki/correlation-workshop) or using git directly using shell commands:
```{bash, eval = FALSE}
git clone https://github.com/bioinformatics-leibniz-hki/correlation-workshop
```
It is highly recommended to run the analysis in an isolated and reproducible environment.
This allows having a fixed set of software versions which can be run on any computer or server without the need of re-installation.
We will use Docker for this:
1. Ensure to activate the CPU virtualization feature in your BIOS if you're running macOS or Windows
2. Download and install [docker](https://docs.docker.com/get-docker/)
3. Open a terminal window and ensure that the command `docker` is available
We can create and start a Docker container containing RStudioServer with all required tools using GNU make:
```{bash, eval = FALSE}
cd correlation-workshop
make
```
The prompt will display the URL in which the environment can be accessed.
The username is `rstudio` with password `password`.
# Computer Science doctorates vs. arcade gaming revenue
Correlation is way to quantify the relationship between two variables.
This relationship is monotonous and often even linear.
We start with looking at a dataset from the U.S. Census Bureau and National Science Foundation showing the number of computer science doctorated and the revenue of arcade games in billion USD [@arcade_data].
First, we load the data using functions from the R [tidyverse](https://www.tidyverse.org/) packages:
```{r}
library(tidyverse)
arcades <- read_csv("data/arcades.csv")
arcades %>% summary()
```
Let's plot one variable against the other and do a linear regression:
```{r}
arcades %>%
ggplot(aes(doctorates, revenue)) +
stat_smooth(method = "lm") +
geom_point() +
labs(
x = "Computer science doctorates",
y = "Arcade revenue (billion USD)"
)
```
# Covariance
Covariance is a simple statistical measure to quantify how much one variable *co-varies* with another.
So why just not use covariance?
```{r}
cov(arcades$doctorates, arcades$revenue)
```
The result is $91.11 Doctorates * bn USD$.
This value is hard to interpret: Is this value high or low? What does the unit mean?
Correlation is just normalized covariance: It does not have a unit and is always in the range $[-1,1]$
# Linear correlation
The higher the number of computer science doctorates, the higher is the revenue in the arcade gaming market!
Correlation values are always ranging between -1 and 1.
The value is negative if one variable continuously increases whereas the other decreases and positive if both variables are either increasing or decreasing.
The value is zero if there is no monotonous relationship.
Let's calculate the linear Pearson's product-moment correlation:
```{r}
cor.test(~ doctorates + revenue, data = arcades, method = "pearson")
```
The correlation coefficient is estimated to be $0.985$ indicating a strong positive relationship which fits with the plot.
Most basic statistical tests, including those for correlations, are actually nothing else than linear models [@tests_as_linear].
The estimated slope of the fitted curve is the strength of the correlation.
We have to normalize our data using z-scaling ($z(x)=\frac{x-\mu}{\sigma}$) to ensure that the estimated slope is independent of the unit and lies between -1 and 1.
This will give us values with a mean of 0 and a variance of 1.
```{r}
arcades_scaled <-
arcades %>%
mutate(
doctorates = doctorates %>% scale(),
revenue = revenue %>% scale()
)
arcades_scaled %>%
pivot_longer(c(doctorates, revenue)) %>%
group_by(name) %>%
summarise(mean = mean(value), variance = var(value))
```
Now we can do a linear regression on one variable using the other as a covariate to get the same correlation coefficient.
We ignore the intercept here because this tell us nothing about the relationship between the two variables and should be almost 0 due to the scaling:
```{r}
lm(formula = doctorates ~ 1 + revenue, data = arcades_scaled) %>% summary()
```
# Ranked correlation
Often, we do not require the relationship to be linear and proportional.
For instance, this is the case if we want to get the correlation of the abundance of a species with time in an exponential growing setting.
Now we don't care about the size of the gradient triangles anymore.
We can remove this effect by ranking the data and doing the linear model again:
```{r}
scale_ranks <- . %>% rank() %>% scale()
arcades_ranked <-
arcades %>%
mutate(
doctorates = doctorates %>% scale_ranks(),
revenue = revenue %>% scale_ranks()
)
arcades_ranked %>%
ggplot(aes(doctorates, revenue)) +
stat_smooth(method = "lm") +
geom_point() +
coord_fixed() +
labs(
x = "Computer science doctorates (rank)",
y = "Arcade revenue (rank)"
)
```
```{r}
lm(formula = doctorates ~ 1 + revenue, data = arcades_ranked) %>% summary()
```
The test is called Spearman's rank correlation:
```{r}
cor.test(~ doctorates + revenue, data = arcades, method = "spearman")
```
Note that the linear correlation coefficient is higher indicating that this relationship is indeed linear:
$r_{pearson} = 0.985 > r_{spearman} = 0.912$
# Partial correlation
One might ask at this point why there is a relationship between the number of computer science doctorates and the arcade revenue.
This question is totally valid and the example dataset was chosen on purpose: To illustrate the ubiquitous phenomena called *spurious correlation*.
Pearson himself already noted this potential for false positive discoveries [@pearson1897mathematical].
This is especially the case if a third confounding variable is influencing both variables in the same way.
Here, this is obviously just a coincidence so the third confounding variable is the time itself.
To mitigate this issue, we control for this third variable by fitting both other variables against the year.
The residuals of the linear model is what can't be explained by time so we can do the correlation test on the residuals:
```{r}
doctorates_residuals <- lm(doctorates ~ year, data = arcades_scaled) %>% residuals()
revenue_residuals <- lm(revenue ~ year, data = arcades_scaled) %>% residuals()
cor.test(~ doctorates_residuals + revenue_residuals, method = "pearson")
```
The linear Pearson correlation is now indeed lower indicating that time is a confounding variable and the relationship is just a coincidence.
This process of doing the test only on a fraction of the total variance (namely the residuals) is called *partial correlation*.
There is also the function `ppcor::pcor.test` doing this:
```{r}
library(ppcor)
pcor.test(
x = arcades_scaled$doctorates,
y = arcades_scaled$revenue,
z = arcades_scaled$year,
method = "pearson"
)
```
# Multilevel correlation
Sometimes, samples are not independent to each other but grouped.
Examples are repeated measurements at multiple time points from the same subject or subjects grouped into different cohorts in a meta study.
This is a fundamental violation of the assumption of statistical tests and can lead to even opposite results which is known as [Simpson's paradox](https://en.wikipedia.org/wiki/Simpson%27s_paradox).
Here we use the R package [correlation](https://easystats.github.io/correlation/index.html) from the [easystats](https://easystats.github.io/easystats/) suite to simulate a relationship between the variables V1 and V2, which has a positive correlation within every group but a negative one on all pooled samples:
```{r}
library(correlation)
data <-
simulate_simpson(n = 100, r = 0.8, groups = 5) %>%
as_tibble()
data %>%
ggplot(aes(x = V1, y = V2)) +
geom_point(aes(colour = Group)) +
geom_smooth(aes(colour = Group), method = "lm", se = FALSE) +
geom_smooth(colour = "black", method = "lm", se = FALSE)
```
The group has an strong contradicting effect on the correlation between V1 and V2.
Thus we have to control for the grouping variable (subject, cohort, etc.).
This can be done using multilevel correlation.
It is analogous to a linear mixed model (LMM) with the grouping variable treated as a random effect.
Unlike partial correlation, the grouping factor here is treated as a random and not as a fixed effect.
We treat a variable as a random effect if it is a factor from which the levels are unknown yet.
For example, there are many other subjects the model has not seen before thus we do not have an estimate for it's slope needed for a fixed effect prediction.
This is a typical use case for random effects, in which the model parameters were drawn from a distribution instead.
Continuously scaled covariates like time or concentration, however, have to be modeled as a fixed effect using partial correlation instead.
Let's use the function `correlation` from the `correlation` package to get the Pearson correlation with and without this multilevel structure in which the sample are nested inside the groups treated as a random effect:
```{r}
correlation(data)
```
```{r}
correlation(data, multilevel = TRUE)
```
The effect size of $r=0.8$ was successfully recovered in the multilevel model.
Here is the analog linear mixed model with a similar result:
```{r}
library(lme4)
lmer(V1 ~ V2 * (1|Group), data = data)
```
It is also possible to have even more levels of samples nestings:
If we have longitudinal data from the same subject in different hospitals we can also write `V1 ~ V2 * (hospital_id|subject_id)` to get the correlation between V1 and V2 controlled for effects related to the subjects and hospitals.
An application of using partial, multilevel and SparCC correlation is given in [@pmid31142858].
Here, age and BMI are modeled as a fixed effect for partial correlation and the subject id as a random effect for multilevel correlation between the abundances of microbes.
Furthermore, the data was normalized using centered log-ratio (clr) to further address the compositionality of relative count data obtained by NGS machines.
# Local correlation
There are relationships between two variables which are statistical depended but can not be discovered using correlation test.
Correlation implies statistical dependency but not vice versa.
This is especially the case in which the two variables are not monotonously linked but in a cyclic way.
Let's simulate the abundance of some predator and some prey species to estimate the relationship of hunting:
```{r}
hunting <-
tibble(time = seq(from = 0, to = 3, length.out = 50)) %>%
mutate(
predator = sin(time),
prey = 1 + cos(time - 0.5)
)
hunting %>%
pivot_longer(
cols = c(predator, prey),
names_to = "animal",
values_to = "abundance"
) %>%
ggplot(aes(time, abundance, color = animal)) +
geom_point()
```
The pearson correlation is almost zero here:
```{r}
cor.test(~ predator + prey, data = hunting, method = "pearson")
```
This is because the relationship between the predator and the prey is not linear:
```{r}
hunting %>%
ggplot(aes(predator, prey)) +
geom_point()
```
But we can still do a correlation test if we just look at a small time window in which the relationship between the predator and the prey can be assumed to be linear:
```{r}
hunting_local <- hunting %>% filter(time > 1 & time < 2)
hunting_local %>%
pivot_longer(
cols = c(predator, prey),
names_to = "animal",
values_to = "abundance"
) %>%
ggplot(aes(time, abundance, color = animal)) +
geom_point() +
stat_smooth(method = "lm")
```
```{r}
cor.test(~ predator + prey, data = hunting_local, method = "pearson")
```
Now we can observe the negative local correlation between the predator and the prey.
An elaborated version of this idea is called Local similarity analysis (LSA) [@ruan2006local]
# More correlations
There are plenty of other ways to define a correlation metric between two continious scaled variables.
For example, there is Kendall’s rank correlation which is a more robust and convervative alternative to Spearman’s rank correlation.
Here is an [overview](https://easystats.github.io/correlation/articles/types.html) about other types of correlations.
# Species and pathway abundance in healthy and disesed cohorts
Let's continue with a more realistic dataset.
We have healthy subjects [@nielsen2014identification] and patients suffering from Colorectal cancer (CRC) [@zeller2014potential].
This dataset contains whole metagenomic sequencing data which was processed by Humann2 to get abundance profiles for bacterial species and pathways.
Data was retrieved using the R-package `curatedMetagenomicData` [@curated_metagenomic_data].
```{r}
features <- read_csv("data/features.csv")
samples <- read_csv("data/samples.csv")
lineages <- read_csv("data/lineages.csv")
samples %>% mutate_if(is.character, as.factor) %>% summary()
```
The R-package `ComplexHeatmap` can be used to create a heatmap showing the abundance profile.
Similar samples and species with a high Spearman correlation are displayed in neighboring rows.
```{r}
library(ComplexHeatmap)
features_mat <-
features %>%
pivot_longer(-sample_id, names_to = "feature", values_to = "abundance") %>%
left_join(lineages) %>%
group_by(feature) %>%
filter(kingdom == "Bacteria" & var(abundance) > 0) %>%
group_by(sample_id) %>%
mutate(abundance = abundance / sum(abundance)) %>%
# long table to wide matrix
ungroup() %>%
select(sample_id, feature, abundance) %>%
pivot_wider(names_from = feature, values_from = abundance) %>%
select(-sample_id) %>%
as.matrix()
Heatmap(
matrix = features_mat,
name = "Abundance (TSS)",
column_title = "Species",
clustering_distance_columns = "spearman",
show_column_names = FALSE,
row_title = "Sample",
clustering_distance_rows = "spearman",
right_annotation = HeatmapAnnotation(
which = "row",
Disease = samples$disease,
Age = samples$age,
Country = samples$country,
Gender = samples$gender
)
)
```
# Sparse correlation
Count data in ecology has often many zeros.
This zero-inflation violates the assumption of a linear model.
It assumes a normal distribution of the residuals (Gauss–Markov theorem).
The majority of the taxa are not present in an average sample and only in a few samples.
Methods like SparCC take this into account [@friedman2012inferring].
We use the function `correlate_spiec_easi_sparcc` inside the source directory which is based on the implementation in SpiecEasi [@layeghifard2018constructing].
This allows us to get an object of class [tidygraph](https://tidygraph.data-imaginist.com/) with one table for the edges and nodes.
```{r}
# load libraries and functions
source("src/setup.R")
features_sparcc <-
lineages %>%
filter(kingdom == "Bacteria") %>%
pull(feature) %>%
head(20)
mat_sparcc <-
features %>%
pivot_longer(-sample_id, names_to = "feature", values_to = "abundance") %>%
left_join(lineages) %>%
filter(feature %in% features_sparcc) %>%
# long table to wide matrix
select(sample_id, feature, abundance) %>%
pivot_wider(names_from = feature, values_from = abundance, values_fill = list(abundance = 0)) %>%
select(-sample_id) %>%
as.matrix()
res_sparcc <- correlate_spiec_easi_sparcc(
data = mat_sparcc,
nodes = lineages,
iterations = 10,
bootstraps = 20
)
res_sparcc
```
Let's plot the network and use functions of the package `ggraph` and `correlate_plot` from this repository:
```{r}
library(ggraph)
res_sparcc %>%
correlate_plot() +
geom_node_point(aes(color = phylum), size = 10) +
geom_node_text(aes(label = feature))
```
# Compositional correlation
Sequencing data is compositional: Instead of counting the species in a absolute way, one just have proportions of the reads assigned to a particular taxon.
This can have severe implications [@gloor2017microbiome].
Imagine one growing species and many constant ones in a longitudinal dataset.
The relative abundance of all other taxa are decreasing, because the library size (total number of reads sequenced) is fixed.
This happens for all other taxa in the same way introducing lots of false positive correlations.
BAnOCC is a tool which takes this compositionality into account [@schwager2017bayesian].
The sum for all abundances must be 1 for each sample.
Let's use their example dataset to get the correlations:
```{r}
library(banocc)
data(compositions_null)
correlate_banocc(compositions_null)
```
A comprehensive tutorial is also [available](https://github.com/biobakery/banocc).
Another way to address the compositionality is to normalize the abundances using centered log-ratios (clr).
# Same correlation
This dinosaur dataset tells us that one can create almost any pattern having the same statistical values including the correlation [@dinosaur_stats; @dinosaur_stats2]:
![](https://d2f99xq7vri1nk.cloudfront.net/DinoSequentialSmaller.gif)
# Which correlation?
Correlation detection strategies in microbial data sets vary widely in sensitivity and precision.
An overview is given in [@weiss2016correlation].
# Causal and directional 'correlation'
Correlation is a symmetric measure to quantify interactions.
However, one might want to know who is the predator and who is the prey.
We need absolute counts e.g. to do causal inference using Bayesian network analysis [@carr2019use].
For instance, this can be archived by spiking the samples with marker cells of known abundance [@rao2021multi].
# Drake workflow
Analyses usually consists if multiple steps which are depended on each other.
We can write this work flow as a tree and use the work flow management R package [drake](https://docs.ropensci.org/drake/).
This has several advantages:
- running multiple steps (called targets in drake) in parallel
- Saving intermediate results
- Rerun only targets which actually changed
```{r}
correlation_plan <- drake_plan(
features = file_in("data/features.csv") %>% read_csv(),
lineages = file_in("data/lineages.csv") %>% read_csv,
feature_types = c("taxon", "pathway"),
cor_methods = c("spearman", "pearson"),
matricies = target({
matrix <-
features %>%
pivot_longer(-sample_id, names_to = "feature", values_to = "abundance") %>%
left_join(lineages) %>%
# get current feature type
filter(feature_type == feature_types) %>%
select(sample_id, feature, abundance) %>%
# subsetting
sample_frac(0.05) %>%
# long table to wide matrix
pivot_wider(
names_from = feature,
values_from = abundance,
values_fill = list(abundance = 0)
) %>%
select(-sample_id) %>%
as.matrix()
tibble(feature_type = feature_types, matrix = list(matrix))
},
dynamic = map(feature_types)
),
correlations = target({
correlation <- correlate(data = matricies$matrix[[1]], method = cor_methods)
tibble(
feature_type = feature_types,
cor_method = cor_methods,
correlation = list(correlation)
)
},
dynamic = cross(feature_types, cor_methods)
)
)
correlation_plan %>% make()
```
Results were stored on hard disk.
They can be loaded into the current R session:
```{r}
loadd(correlations)
correlations
```
A more elaborated work flow is part of this repository (See [report](src/report.html)).
It includes also the part of getting the data.
Drake plans are tibbles of steps and can be plotted:
```{r}
plan %>% plot()
```
The targets can be made by running the script `analyze.R`.
It is recommended to put this as a background job of RStudio to run it in an isolated environment.
Sometimes cache directories are not created in the first run.
It is recommended to run the job again if it fails.
```{r, eval=FALSE}
rstudioapi::jobRunScript("analyze.R")
```
# Ensemble correlation
Often, an edge is only considered if it is significant in multiple correlation methods.
These *ensemble approaches* tend to be more robust having less false positive interactions:
```{r}
loadd(coabundances)
graphs <-
coabundances %>%
filter(feature_type == "pathway" & disease == "CRC") %>%
select(method, coabundance) %>%
deframe()
ensemble_coabundance(
x = graphs$spearman,
name_x = "spearman",
y = graphs$banocc,
name_y = "banocc",
method = "intersection"
)
```
# No correlation but covariance
Correlation assumes that the pair of two variables are *conditionally independend* from all others.
But often, an interaction is only there in a presence or absence if a third variable.
SpiecEasi tries to account for this [@kurtz2015sparse].
An application of this is finding relationships between features of different types.
Let's load both species and pathways from the Colorectal Cancer (CRC) cohort from the main plan in this repository (20 samples and 20 features each).
```{r}
loadd(inter_feature_type_mats)
matricies_crc <-
inter_feature_type_mats %>%
filter(disease == "CRC") %>%
pull(mat) %>%
first()
matricies_crc %>% map(dim)
```
Let's estimate covariance relationships:
```{r}
crc_spiec_easi <- matricies_crc %>% correlate_spiec_easi(method = "mb", nodes = lineages)
crc_spiec_easi
```
```{r}
crc_spiec_easi %>% correlate_plot()
```
These are the relationships found between a species and a pathway:
```{r}
crc_spiec_easi %>%
activate(edges) %>%
as_tibble() %>%
filter(from_feature_type != to_feature_type) %>%
select(from_feature, to_feature, estimate)
```
# Network analysis
These correlation networks were created by the main drake work flow:
```{r}
loadd(coabundances)
coabundances
```
The tidygraph package provides functions to calculate node and edge attributes based on the topological structure:
```{r}
coabundances$coabundance[[1]] %>%
activate(nodes) %>%
mutate(
# number of edges connected to a node
degree = centrality_degree(),
# Kleinberg's hub centrality scores
hub = centrality_hub()
) %>%
as_tibble() %>%
select(feature, degree, hub)
```
Objects created by `correlate` are shipped with basic topology metrics.
We can extract them to make plot for comparison:
```{r}
coabundances %>%
filter(feature_type == "all") %>%
select(-feature_type) %>%
mutate(nodes = coabundance %>% map(~ .x %>% activate(nodes) %>% as_tibble)) %>%
select(-coabundance) %>%
unnest(nodes) %>%
pivot_longer(cols = c(degree, closeness, betweeness), names_to = "metric") %>%
ggplot(aes(feature_type, value)) +
geom_boxplot() +
facet_wrap(~metric, scales = "free_y") +
labs(x = "Feature type", y = "Topology score")
```
Or compare taxonomic correlations between healthy and diseased cohorts:
```{r}
coabundances %>%
filter(feature_type == "taxon" & method == "sparcc") %>%
select(-feature_type) %>%
mutate(nodes = coabundance %>% map(~ .x %>% activate(nodes) %>% as_tibble)) %>%
select(-coabundance) %>%
unnest(nodes) %>%
pivot_longer(cols = c(degree, closeness, betweeness), names_to = "metric") %>%
ggplot(aes(disease, value)) +
geom_boxplot() +
ggpubr::stat_compare_means() +
facet_wrap(~metric, scales = "free_y")
```
The graph with all attributes of edges and nodes can be saved as a file e.g. to visualize it in other tools like [Cytoscape](https://cytoscape.org/):
```{r}
library(igraph)
coabundances %>%
filter(
disease == "healthy" &
feature_type == "pathway" &
method == "spearman"
) %>%
pull(coabundance) %>%
first() %>%
as.igraph() %>%
write.graph("healthy_pathway_spearman.graphml", format = "graphml")
```
# References