[R] numbers loop in R

hadley wickham h.wickham at gmail.com
Fri Apr 17 19:47:18 CEST 2009


On Fri, Apr 17, 2009 at 12:19 PM, jim holtman <jholtman at gmail.com> wrote:
> try this:
>
>> matrixx<-function(A){
> +     B=matrix(NaN,nrow=(A+1),ncol=4)
> +     k <- 1
> +     for (i in 3:A){
> +         for (j in i:A) {
> +             B[k,] <- c(NaN, i-2, i-1, j)
> +             k <- k + 1
> +         }
> +     }
> +     B
> + }
>> matrixx(5)
>     [,1] [,2] [,3] [,4]
> [1,]  NaN    1    2    3
> [2,]  NaN    1    2    4
> [3,]  NaN    1    2    5
> [4,]  NaN    2    3    4
> [5,]  NaN    2    3    5
> [6,]  NaN    3    4    5

Here's a solution without the loop.  I think it illustrates the intent
of the algorithm more clearly.

candidates <- t(combn(5,3))
firstdiff <- candidates[,2] - candidates[, 1]
cbind(NaN, candidates[firstdiff == 1, ])

Hadley

-- 
http://had.co.nz/




More information about the R-help mailing list