0

我正在寻找一种通用方法来处理需要组合但数据并不总是满足combn函数假设的情况。

具体来说,我有一个国会议员及其委员会任务的数据框。为了检查这个政治家网络,我想将属于同一委员会的任何成员联系起来(即在它们之间建立联系)。

数据如下所示:

name_id     assignment
 A000374    Agriculture
 A000370    Agriculture
 A000055 Appropriations
 A000371 Appropriations
 A000372    Agriculture
 A000376        Foreign

因此,生成的网络数据应如下所示:

from       to          committee
A000374    A000370     Agriculture
A000055    A000371     Appropriations

问题是我的代码(下面)会引发错误,因为并不总是存在配对(代码中的 ncombn 命令可以识别这种情况。这是正确的方法吗?如果是,如何创建一个通常解决此问题的命令?

这是我的代码,目前:

library(RCurl)
x <- getURL("https://raw.githubusercontent.com/bac3917/Cauldron/master/cstack.csv")
cstack <- read.csv(text = x)

# split the string into two columns that represent name_id and committee assignment
cstack <- cstack %>% separate(namePaste, c("name_id","assignment")) 

# use combn and dplyr to create pairs (results in error)
edges<-cstack %>% 
  group_by(assignment) %>%
  do(as.data.frame(t(combn(.[["name_id"]], 2)))) %>%
  group_by(V1, V2) %>% 
  summarise(n( ))
4

1 回答 1

1

正如本所说,combn(x, 2)不适用于x < 2. combn您可以定义一个仅在 时计算的函数x > 1。下面是一个data.table版本。

library(data.table)
cstack <- fread("https://raw.githubusercontent.com/bac3917/Cauldron/master/cstack.csv",
    header=TRUE)[, tstrsplit(sub(" ", "\01", namePaste), "\01")]
setnames(cstack, c("name_id","assignment"))
mycomb <- function(x) if(length(x) > 1) data.table(t(combn(x, 2)))
cstack <- cstack[, mycomb(name_id), by = "assignment"]
setcolorder(cstack, c(2,3,1))
setnames(cstack, c("V1", "V2"), c("from", "to"))
cstack
#>           from      to      assignment
#>     1: A000374 A000370     Agriculture
#>     2: A000374 A000372     Agriculture
#>     3: A000374 A000378     Agriculture
#>     4: A000374 B001298     Agriculture
#>     5: A000374 B001307     Agriculture
#>    ---                                
#> 12957: C001053 L000491  Ranking Member
#> 12958: C001053 R000582  Ranking Member
#> 12959: D000619 L000491  Ranking Member
#> 12960: D000619 R000582  Ranking Member
#> 12961: L000491 R000582  Ranking Member
于 2020-02-28T00:37:06.320 回答