Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Transform dagitty DAG to formatted string for ggdag #90

Closed
lorenzoFabbri opened this issue Mar 31, 2023 · 3 comments · Fixed by #117
Closed

Transform dagitty DAG to formatted string for ggdag #90

lorenzoFabbri opened this issue Mar 31, 2023 · 3 comments · Fixed by #117

Comments

@lorenzoFabbri
Copy link

I usually start creating my DAGs with the web version of dagitty, altough I appreciate the R-like style offered by ggdag. I looked for a function to transform a dagitty object to a formatted string to use within ggdag. I did not find anything so I wrote the following function:

#' Convert a \pkg{dagitty} DAG to a formatted string
#'
#' @description
#' Convert a DAG from \pkg{dagitty} to a formatted
#' string that can be used to create DAGs with \pkg{ggdag}
#' using its formula-based input method.
#'
#' @examples
#' myphd::from_dagitty_to_ggdag(dag)$dag_formula %>% cat(sep = "\n")
#'
#' @param dag A \pkg{dagitty} DAG. A string.
#' @returns A formatted string.
#' @export
from_dagitty_to_ggdag <- function(dag) {
  dag <- dagitty::dagitty(dag)

  to_ggdag <- ggdag::tidy_dagitty(dag) |>
    (\(x) x$data) () |>
    dplyr::select(name, to) |>
    dplyr::rename(from = name) |>
    dplyr::group_by(to) |>
    dplyr::summarise(from_formula = paste(from, collapse = " + ")) |>
    tidyr::drop_na(to) |>
    tidyr::unite(dag_formula, to, from_formula, sep = " ~ ")

  return(to_ggdag)
}

This basically returns a formatted string in the required R-like style for ggdag. Would something like this be useful?

@malcolmbarrett
Copy link
Collaborator

Can you tell me more about your motivation for a function like this? I don't think there's anywhere in ggdag that requires you to use dagify()'s R-like syntax. Is the point of this to translate the dagitty syntax to the R-like syntax just in case you prefer the latter?

dagify() creates dagitty-style syntax under the hood (you can use it directly with dagitty::dagitty()), so it would be translating it from the dagitty-style syntax to the R-style syntax back to the dagitty-style syntax

@malcolmbarrett
Copy link
Collaborator

I'm going to close this, but if you think it's still worth discussing, feel free to re-open

@malcolmbarrett
Copy link
Collaborator

I do have a use case for this, actually, which is to update a data frame, then sync the dagitty object to match. I'm going to use a modified version of your code for that

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants