0

I have a matrix (but for the purposes of the example I will simplify to a vector).

I want to loop over all pairs of the list. So if the list is length n (or the matrix has n columns), the resulting list has to be (n choose 2) items long.

Suppose n = 6 for the example, but in reality is 36.

Basically, I want a loop like this:

list=1:6

endlist= vector("list", 15)   # 15 from 6!/((4!)(2!))

Here is what I want:

Note the below loop does NOT work since there is no i index, and there appears to be no linear combination of j and k that fits the index. Is there a nonlinear one? Or is there a better way to program this?

for(j in 1:5){  
    for(k in (j+1):6){
        endlist[[i]]=list[j]*list[k] 
    }
}

Giving the output:

endlist=
[[1]]
[1] 2 3 4 5 6 

[[2]]
[1] 6 8 10 12 

etc.

4

1 回答 1

2

肯定有更好的编码方式。我不确定这将如何必然适用于您的矩阵,但对于您的示例:

combn(list, 2, prod)
#[1]  2  3  4  5  6  6  8 10 12 12 15 18 20 24 30

combn()产生一个向量的组合,并且可以对每个组合应用一个函数(prod)。如果你真的想要输出作为一个列表,你可以这样做split()

split(combn(list, 2, prod), rep(1:(max(list)-1), times =(max(list)-1):1))
# $`1`
# [1] 2 3 4 5 6
# 
# $`2`
# [1]  6  8 10 12
# 
# $`3`
# [1] 12 15 18
# 
# $`4`
# [1] 20 24
# 
# $`5`
# [1] 30

我认为这里的要点是,最好计算你的组合并处理这些组合,而不是自己在某种循环中创建组合。

于 2013-09-15T06:25:22.630 回答