R语言 调整网络数据,使边双向延伸

7ajki6be  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(161)

我有一个数据框架,包含一个人的列表和他们的邻居。然而,数据表明乔希是他自己,艾玛和尼克的邻居,但艾玛不是乔希的邻居。

x <- read.table(text = "
Name ID Neighbour_ID
Josh 1 1,2,3
Emma 2 4
Nick 3 1
Mark 4 5
Claire 5 
", sep = " ", header = TRUE)

x

 Name     ID      Neighbour_ID
1   Josh  1      1,2,3
2   Emma  2          4
3   Nick  3          1
4   Mark  4          5
5 Claire  5

这当然需要修正,我正在寻找一种方法来做到这一点。结果应该是这样的

Name     ID      Neighbour_ID
1   Josh  1        2,3
2   Emma  2        1,4
3   Nick  3          1
4   Mark  4        2,5
5 Claire  5          4

补充:如果您发现一个更适合这个问题的标题,请随时编辑!

cbeh67ev

cbeh67ev1#

使用 igraph 包,将其转换为图形对象:

library(dplyr)
library(tidyr)
library(igraph)

g <- separate_rows(x, Neighbour_ID, convert = TRUE) %>% 
  select(from = ID, to = Neighbour_ID) %>% 
  filter(!is.na(to) & from != to) %>% 
  graph_from_data_frame(directed = FALSE)

g
# IGRAPH 1eeedee UN-- 5 5 -- 
# + attr: name (v/c)
# + edges from 1eeedee (vertex names):
#   [1] 1--2 1--3 2--4 1--3 4--5
plot(g)

我会在这里停止,因为我们的数据是 graph 格式的。但是如果你需要你的输出是 * data.frame *,那么就得到 edgelists 并合并回原始数据。

gEdge <- get.edgelist(g)
left_join(x %>% select(Name, ID),
          data.frame(unique(rbind(gEdge[, 1:2], gEdge[, 2:1]))) %>%
            mutate(X1 = as.integer(X1), X2 = as.integer(X2)) %>% 
            summarise(Neighbour_ID = paste(sort(X2), collapse = ","), .by = X1),
          by = c("ID" = "X1"))

#     Name ID Neighbour_ID
# 1   Josh  1          2,3
# 2   Emma  2          1,4
# 3   Nick  3            1
# 4   Mark  4          2,5
# 5 Claire  5            4
nsc4cvqm

nsc4cvqm2#

x %>%
  separate_rows(Neighbour_ID, convert = TRUE) %>% 
  select(-Name) %>%
  rbind(setNames(rev(.), names(.))) %>%
  filter(ID != Neighbour_ID) %>%
  distinct()%>%
  left_join(select(x, -Neighbour_ID), c(ID = 'ID')) %>%
  summarise(Neighbour_ID = toString(sort(Neighbour_ID)), .by = c(Name, ID))

  # A tibble: 5 × 3
  Name      ID Neighbour_ID
  <chr>  <int> <chr>       
1 Josh       1 2, 3        
2 Emma       2 1, 4        
3 Nick       3 1           
4 Mark       4 2, 5        
5 Claire     5 4

相关问题