2014-10-31 48 views
2

我想创建一个包含n数字(n<m)的所有可能的代码(m标志)的列表。例如,对于n=2m=4我想:如何列出m标志中的所有n长度代码?

0000 
0001 
0010 
0011 
0100 
0101 
0110 
0111 
1000 
1001 
1010 
1011 
1100 
1101 
1110 
1111 

为0,1,2:

0000 
0001 
0002 
0010 
0011 
0012 
0020 
0021 
0022 
0100 
0101 
0102 
0110 
0111 
... 
2220 
2221 
2222 

等。任何想法如何?

回答

2

您可以在自定义函数中使用函数permutations从包装gtools这样的:

library(gtools) 
## 
foo <- function(m,n,data=NULL) 
{ 
    if(is.null(data)){ 
    data <- 0:(n-1) 
    } 
    ## 
    mat <- gtools::permutations(
    n,m,data, 
    repeats.allowed=T) 
    ## 
    apply(mat,1,function(X){ 
    Reduce(function(x,y){ 
     paste0(x,y) 
    },X) 
    }) 
} 
## 

所以对于m=4n=2

> foo(4,2) 
[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110" 
[8] "0111" "1000" "1001" "1010" "1011" "1100" "1101" 
[15] "1110" "1111" 

m=4n=3

> foo(4,3) 
[1] "0000" "0001" "0002" "0010" "0011" "0012" "0020" 
[8] "0021" "0022" "0100" "0101" "0102" "0110" "0111" 
[15] "0112" "0120" "0121" "0122" "0200" "0201" "0202" 
[22] "0210" "0211" "0212" "0220" "0221" "0222" "1000" 
[29] "1001" "1002" "1010" "1011" "1012" "1020" "1021" 
[36] "1022" "1100" "1101" "1102" "1110" "1111" "1112" 
[43] "1120" "1121" "1122" "1200" "1201" "1202" "1210" 
[50] "1211" "1212" "1220" "1221" "1222" "2000" "2001" 
[57] "2002" "2010" "2011" "2012" "2020" "2021" "2022" 
[64] "2100" "2101" "2102" "2110" "2111" "2112" "2120" 
[71] "2121" "2122" "2200" "2201" "2202" "2210" "2211" 
[78] "2212" "2220" "2221" "2222" 

等...

+0

非常感谢。这正是我所说的。 – jjankowiak 2014-10-31 23:01:44

0

您也可以考虑iterpc包。

library(iterpc) 
foo = function(m, n){ 
    I = iterpc(n, m, ordered=T, replace=T) 
    apply(getall(I)-1, 1, function(r) paste(r, collapse="")) 
} 

> foo(4,2) 
[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110" "0111" "1000" 
[10] "1001" "1010" "1011" "1100" "1101" "1110" "1111" 
相关问题