0
我想通過創建2個數據幀在R中創建一個有向圖:一個用於頂點,一個用於邊。此外,我的圖表應具有以下屬性:在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和B - > A)。我怎麼能在A和B之間只有一條邊?
親切的問候
編輯:我發現了一個解決方案來源: 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"))
請提供[MCVE] –
我發現這裏的解決方案:http://stackoverflow.com/questions/28574006/unique-combination-of-two-columns-in-r –
@StevenBeaupré:我已經發布代碼。 –