过滤表中的定向共现

时间:2018-07-25 07:10:57

标签: r igraph tidyverse tidygraph

我有同时出现的数据,可以在两列中表示。每列中的条目来自同一组可能性。最终,我的目标是绘制一个有向网络,但首先,我想将表格分为相互可逆的表(即X-> Y和Y-> X)和仅在一个方向上进行的表(即仅Y-> Z )。这是一个示例:

library(tidyverse)

# Example data
from <-  c("A", "B", "F", "Q", "T", "S", "D", "E", "A", "T", "F")
to <- c("E", "D", "Q", "S", "F", "T", "B", "A", "D", "A", "E")
df <- data_frame(from, to)
df
# A tibble: 11 x 2
   from  to   
   <chr> <chr>
 1 A     E    
 2 B     D    
 3 F     Q    
 4 Q     S    
 5 T     F    
 6 S     T    
 7 D     B    
 8 E     A    
 9 A     D    
10 T     A    
11 F     E   

这是我想要的输出:

# Desired output 1 - reciprocal co-occurrences
df %>% 
  slice(c(1,2)) %>% 
  rename(item1 = from, item2 = to)

# A tibble: 2 x 2
  item1 item2
  <chr> <chr>
1 A     E    
2 B     D

# Desired output 2 - single occurrences
df %>% 
  slice(c(3,4,6,6,9,10,11))

# A tibble: 7 x 2
  from  to   
  <chr> <chr>
1 F     Q    
2 Q     S    
3 S     T    
4 S     T    
5 A     D    
6 T     A    
7 F     E 

如果同现是互惠的,那么条目的顺序无关紧要,我只需要它们的名称就可以了,我不需要知道方向。

这感觉像一个图形问题,所以我试了一下,但是不熟悉这种类型的数据,大多数教程似乎都涵盖了无向图。看看我了解的tidygraph软件包使用的igraph软件包,我已经尝试过:

library(tidygraph)

df %>% 
  as_tbl_graph(directed = TRUE) %>%
  activate(edges) %>% 
  mutate(recip_occur = edge_is_mutual()) %>% 
  as_tibble() %>%
  filter(recip_occur == TRUE) 
# A tibble: 4 x 3
   from    to recip_occur
  <int> <int> <lgl>      
1     1     8 TRUE       
2     2     7 TRUE       
3     7     2 TRUE       
4     8     1 TRUE   

但是,这会使节点的边缘分离,并重复相互出现。有没有人对这种数据有经验?

1 个答案:

答案 0 :(得分:1)

尝试一下:

数据:

from <-  c("A", "B", "F", "Q", "T", "S", "D", "E", "A", "T", "F")
to <- c("E", "D", "Q", "S", "F", "T", "B", "A", "D", "A", "E")
df <- data_frame(from, to)

代码:

recursive_IND <-
1:nrow(df) %>% 
sapply(function(x){
    if(any((as.character(df[x,]) == t(df[,c(2,1)])) %>% {.[1,] & .[2,]}))
        return(T) else return(F)
    })

df[recursive_IND,][!(df[recursive_IND,] %>% apply(1,sort) %>% t %>% duplicated(.)),]
df[!recursive_IND,]

结果:

# A tibble: 2 x 2
#  from  to   
#  <chr> <chr>
#1 A     E    
#2 B     D    

# A tibble: 7 x 2
#  from  to   
#  <chr> <chr>
#1 F     Q    
#2 Q     S    
#3 T     F    
#4 S     T    
#5 A     D    
#6 T     A    
#7 F     E