【问题标题】:Creating formula from matrix in R从R中的矩阵创建公式
【发布时间】:2021-10-25 22:17:38
【问题描述】:

我在 R 中有一个这样的数据框

预期输入:

arc.set <- matrix(c("Q", "A",
                    "G", "A",
                    "G", "D",
                    "D", "A"),
                  byrow = TRUE, ncol = 2,
                  dimnames = list(NULL, c("from", "to")))
from to
Q    A
G    A
G    D
D    A

我想根据上面的矩阵制作一个这样的公式。基本上“to”列中有两个唯一字母,我想从“from”列中获取与“to”列中的唯一字母相关的每个唯一字母,格式如下:

to_col ~ from_col_1 + ... + from_col_n

基本上用户会指定曝光和结果,所以我不担心那块。

预期输出:

tidy_ggdag <- dagify(
  A ~ D + G + Q,
  D ~ G,
  exposure = "G",
  outcome = "A"
) %>% 
  tidy_dagitty()

【问题讨论】:

    标签: r matrix directed-acyclic-graphs


    【解决方案1】:

    也许这会有所帮助

    with(
      aggregate(
        . ~ to,
        unique(as.data.frame(arc.set)),
        paste0,
        collapse = "+"
      ),
      sapply(paste0(to, "~", from), as.formula)
    )
    

    你会看到

    $`A~Q+G+D`
    A ~ Q + G + D
    <environment: 0x000000001af2b280>
    
    $`D~G`
    D ~ G
    <environment: 0x000000001af2b280>
    

    【讨论】:

    • 谢谢!但是我如何将它们都放在一个用逗号分隔的长字符串中?
    • @Eisen 也许您可以尝试使用do.call(dagify, c(f, exposure = "G", outcome = "A"),其中f 是我的代码的输出。
    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多