Extract mediator nodes lying on directed paths from exposure to outcome.
Parameters:
| Name |
Type |
Description |
Default |
as_string
|
bool
|
When True, return a formatted string representation of mediator
sets. Defaults to False to return a list of lists.
|
False
|
Returns:
| Type |
Description |
list[list[str]] or str
|
Mediator nodes grouped by directed path when as_string is
False; otherwise a string representation of the same structure.
|
Examples:
>>> G = DAG(graph="X -> M -> Y")
>>> G.mediators()
[['M']]
>>> G.mediators(as_string=True)
'[[M]]'
Source code in causalinf/gcm.py
| def mediators(self, as_string=False):
"""
Extract mediator nodes lying on directed paths from exposure to outcome.
Parameters
----------
as_string : bool, optional
When ``True``, return a formatted string representation of mediator
sets. Defaults to ``False`` to return a list of lists.
Returns
-------
list[list[str]] or str
Mediator nodes grouped by directed path when ``as_string`` is
``False``; otherwise a string representation of the same structure.
Examples
--------
>>> G = DAG(graph="X -> M -> Y")
>>> G.mediators()
[['M']]
>>> G.mediators(as_string=True)
'[[M]]'
"""
paths = self.paths(directed=True)
paths = [p.split('->') for p in paths]
exposure = self.exposure
outcome = self.outcome
res = []
for path in paths:
res += [[var.strip() for var in path if var.strip() not in exposure + outcome]]
res = [l for l in res if len(l)>0]
if as_string:
res = f"[{', '.join([f"[{', '.join(l) }]" for l in res])}]"
return res
|