首页 文章

在R中提取社交网络结构

提问于
浏览
1

我正在尝试为网络分析准备一个特定的数据集,但首先,我需要从该数据中提取节点之间的关系 . 数据以以下格式显示:

id  | structure_var
1   | 1
2   | 1.1
3   | 1.2
4   | 1.2.1
5   | 1.2.2
6   | 1.3
7   | 2
8   | 2.1
9   | 2.1.1

所需的输出是这个(来自和对应于上面的ID值):

from  | to
    1  | 2
    1  | 3
    1  | 6
    3  | 4
    3  | 5
    7  | 8
    8  | 9

到目前为止我能想出的最好的是:

library(stringr)
extract_structure = function(x,y=seq_along(x),connections=character()){

  depth  = str_count(x,"\\.")
  parent = gsub("(\\d+)\\..*","\\1",x)
  parent_iterator = as.numeric(unique(parent))


  for(i in parent_iterator){
    a = y[which(x==as.character(i))]
    b = y[which(depth==1 & parent==i)]
    if(length(a)>0 & length(b)>0){connections = c(connections,paste(a,b,sep="-"))}
  }

  zero_depth = which(depth<1)
  next_y = y[-zero_depth]
  next_x = gsub("^\\d+\\.","",x[-zero_depth])

  if(sum(depth)>0){extract_structure(x=next_x,y=next_y,connections=connections)} 
    else{return(connections)}
}


extract_structure(x=comment_structure)
"1-2" "1-3" "1-6" "7-8" "2-9" "8-9" "3-4" "3-5"

但正如你所看到的,答案并没有保留历史,这就是它不应该连接2和9的原因 . 有没有人对如何最佳编程有任何建议?

非常感谢!

1 回答

  • 1

    这可以通过字符串处理非常容易地完成 .

    library(dplyr)
    library(stringi)
    
    merge(data %>% rename(from_ID = id, 
                          from_structure = structure_var),
          data %>% rename(to_ID = id, 
                          to_structure = structure_var) ) %>%
      filter(paste0("^", from_structure , "\\.[0-9]$") %>%
               stri_detect_regex(to_structure, .) )
    

相关问题