我想创建一个包含m
个数字(n
)的所有可能代码(n<m
符号)的列表。例如,我希望获得n=2
和m=4
:
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
等等。有什么想法吗?
答案 0 :(得分: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=4
和n=2
,
> foo(4,2)
[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110"
[8] "0111" "1000" "1001" "1010" "1011" "1100" "1101"
[15] "1110" "1111"
和m=4
,n=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"
等...
答案 1 :(得分: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"