将可变长度列表转换为边列表igraph R

Convert variable length list into edge list igraph R

我在 R 中有一个列表,其中每个元素都有可变数量的字符串,例如:

el: list
chr [1:3] "sales", "environment", "communication"
chr [1:2] "interpersonal", "microsoft office"
chr [1:4] "writing", "reading", "excel", "python"

我想将此列表转换为 2 列矩阵,将两个字符串并排放置,如果它们出现在列表的相同元素中,例如

matrix:
"sales", "environment"
"sales, "communication"
"environment", "communication"
"interpersonal", "microsoft office"
"writing", "reading"
"writing", "excel"
"writing", "python"
"reading", "excel"
"reading", "python"
"excel", "python"

我该怎么做?

如果我们需要matrix中的输出,我们可以使用combn

do.call(rbind, lapply(lst, function(x) t(combn(x, 2))))
#     [,1]            [,2]              
# [1,] "sales"         "environment"     
# [2,] "sales"         "communication"   
# [3,] "environment"   "communication"   
# [4,] "interpersonal" "microsoft office"
# [5,] "writing"       "reading"         
# [6,] "writing"       "excel"           
# [7,] "writing"       "python"          
# [8,] "reading"       "excel"           
# [9,] "reading"       "python"          
#[10,] "excel"         "python"    

或者如@thelatemail 所述,通过 unlist 调用 'lst'

调用 t 一次可能比多次调用更快
matrix(unlist(lapply(lst, combn, 2)), ncol=2, byrow=TRUE)