【问题标题】:Sampling a graph in R在 R 中对图进行采样
【发布时间】:2016-05-26 13:21:00
【问题描述】:

我想通过制作 2 个数据框在 R 中制作有向图:一个用于顶点,一个用于边。此外,我的图表应该具有以下属性:

  • 没有圆圈(因此没有 A -> A)
  • 2 个节点之间最多有 1 条边。

我想出了如下代码:

library(dplyr)

USER_BASE <- 1:100
MAXIMUM_USER_RELATIONSHIP = length(USER_BASE)*4

my_random <- function(vector, size, replace, seed)
{
    set.seed(seed)
    return(sample(vector, size = size, replace = replace))
}

user <- data.frame(
    id = USER_BASE
)

relationship <- data.frame(
    from = my_random(USER_BASE, MAXIMUM_USER_RELATIONSHIP, replace = TRUE, 1),
    to = my_random(USER_BASE, MAXIMUM_USER_RELATIONSHIP, replace = TRUE, 2)
) %>% filter(from != to) %>% unique()

我的代码仍然允许 2 个节点(A -> B 和 B -> A)之间有 2 条边。我怎样才能在 A 和 B 之间实现只有 1 个边缘?

亲切的问候

编辑:我找到了一个解决方案: Unique rows, considering two columns, in R, without order

我的完整代码:

library(dplyr)
library(data.table)

USER_BASE <- 1:100
MAXIMUM_USER_RELATIONSHIP = length(USER_BASE)*4

my_random <- function(vector, size, replace, seed)
{
    set.seed(seed)
    return(sample(vector, size = size, replace = replace))
}

user <- data.frame(
    id = USER_BASE
)

relationship <- data.frame(
    from = my_random(USER_BASE, MAXIMUM_USER_RELATIONSHIP, replace = TRUE, 1),
    to = my_random(USER_BASE, MAXIMUM_USER_RELATIONSHIP, replace = TRUE, 2)
) %>% filter(from != to) %>% unique()

relationship <- unique(as.data.table(relationship)[, c("from", "to") := list(pmin(from, to),
                                                 pmax(from, to))], by = c("from", "to"))

【问题讨论】:

标签: r graph reproducible-research


【解决方案1】:

您可以使用anti_join 删除任何存在于反转版本中的行。

reverse <- data.frame(to = relationship$from, from = relationship$to)

anti_join(relationship, reverse)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多