2016-06-15 59 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