頂点用とエッジ用の 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 つのノード間で 2 つのエッジが許可されています (A -> B AND B -> A)。A と B の間のエッジを 1 つだけにする方法を教えてください。
敬具
編集:私は解決策を見つけました: Rの2つの列を考慮した一意の行、順序なし
私の完全なコード:
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"))