2016-06-15 46 views
3

我有R中的列表,其中每个元素具有可变数量的字符串,例如:转换可变长度列表分成边列表的igraphř

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" 

我该如何解决这个问题?

回答

3

如果我们需要在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调用t比多次一旦荷兰国际集团的“善堂”

matrix(unlist(lapply(lst, combn, 2)), ncol=2, byrow=TRUE) 
+2

很好的答案。可能稍微快一点,将'unlist'并且输入矩阵 - '矩阵(unlist(lapply(el,combn,2)),ncol = 2,byrow = TRUE) - 虽然没有测试过.. – thelatemail

+0

@thelatemail谢谢,我没有正确检查。 – akrun