No need for loops (lapply
or otherwise):
combn(1:4,2)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 1 2 2 3
# [2,] 2 3 4 3 4 4
Example with calculating the sums of combinations:
combn(1:4,2,FUN=sum)
# [1] 3 4 5 5 6 7
An example with a user defined function:
x <- 11:14
combn(1:4,2,FUN=function(i,a) sum(a[i]),a=x)
#[1] 23 24 25 25 26 27
Here (in the anonymous function) i
is the combination used as index and argument a
is a vector to which I pass x
.
And the same with a user-defined named function:
fun <- function(i,a) sum(a[i])
combn(1:4,2,FUN=fun,a=x)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…