我有一个元素列表{1,2,3,4,5},我想找到每个元素的所有组合,即{1,2,3,4,5,12,13,14 R,15,23,24,25,34,35等 这有内置功能吗?
答案 0 :(得分: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()
的循环,而第一个版本是完全矢量化的。
答案 1 :(得分: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
是组合的矢量来源(x
in 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