2016-03-28 122 views
-2

我有一個元素列表{1,2,3,4,5},我想查找每個元素的所有組合,即{1,2,3,4,5, 12,13,14,15,23,24,25,34,35等等} in R 這是否有任何內置功能?查找每個元素的組合

+2

你正在尋找 功能是'combn()' –

回答

0

你可以試試這個:

g1 <- expand.grid(0:5,1:5) #create a data.frame with all combinations 
v <- as.numeric(paste0(g1[,1], g1[,2])) #convert combinations into numbers 
v <- sort(v[(v%%11)!=0]) #sort and remove duplicate figures, like 44 or 55 
v 
#[1] 1 2 3 4 5 12 13 14 15 21 23 24 25 31 32 34 35 41 42 43 45 51 52 53 54 

相同的代碼可以寫在一個稍微更緊湊的方式:

v <- sort(as.numeric(apply(expand.grid(0:5,1:5), 1, paste, collapse=""))) 
v <- v[!!v%%11] 

如果性能問題,這種較短的版本很可能會慢一些,因爲它在第一個版本完全向量化時使用與apply()的循環。

0

這是你在找什麼?

unlist(lapply(1:2, function(m) apply(combn(1:5, m), 2, function(x) as.numeric(paste0(as.character(x), collapse=""))))) 
[1] 1 2 3 4 5 12 13 14 15 23 24 25 34 35 45 

1:2是要素數的選擇範圍(也m?combn),和1:5組合的載體源(combnx)。

這裏是做它的功能:

range_combn <- function(x, m){ 
    unlist(lapply(m, function(m) apply(combn(x, m), 2, 
     function(x) as.numeric(paste0(as.character(x), collapse=""))))) 
} 

如:

range_combn(1:5, 1:3) 
[1] 1 2 3 4 5 12 13 14 15 23 24 25 34 35 45 123 124 125 134 135 145 234 235 245 345 

range_combn(1:5, 1:2) 
[1] 1 2 3 4 5 12 13 14 15 23 24 25 34 35 45 
相關問題