【发布时间】:2016-03-28 04:31:52
【问题描述】:
我有一个元素列表 {1,2,3,4,5},我想找到每个元素的所有组合,即 {1,2,3,4,5,12,13,14 R中的,15,23,24,25,34,35等} 是否有任何内置功能?
【问题讨论】:
-
你要找的函数是
combn()
标签: r combinations
我有一个元素列表 {1,2,3,4,5},我想找到每个元素的所有组合,即 {1,2,3,4,5,12,13,14 R中的,15,23,24,25,34,35等} 是否有任何内置功能?
【问题讨论】:
combn()
标签: r combinations
这就是你要找的吗?
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 是要选择的元素数量范围(也可以是?combn 中的m),1:5 是组合的向量源(x 中combn)。
这是一个功能:
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
【讨论】:
你可以试试这个:
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() 的循环,而第一个版本是完全矢量化的。
【讨论】: