Home > Enterprise >  How to run two indices in r
How to run two indices in r

Time:12-22

I am struggeling with a VERY simple problem :

I would like to run 2 indices combinations in a loop : i=1,j=1, i=1,j=2,i=1,j=3..... then switch to i=1,j=2 i=2,j=2 i=3,j=2... and so on until i=n,j=n

I wrote the following code which sadly doesn't work properly :

  • I cannot use r functions such as expand.grid etc..
a <- function(n) {
  for (i in 1:n)  {
    for (j in 1:n) {
     print(i,j)
    }
  }
}

#I expect to get 1,1 1,2 1,3 1,4... 2,1 2,2... but this is not the result.

Thank you in advance,

CodePudding user response:

Your code does work! Just printing with comma only prints the first.

Instead try separating by comma in a string:

a <- function(n) {
  for (i in 1:n)  {
    for (j in 1:n) {
     print(paste(i, j, sep=', '))
    }
  }
}

Ex:

> a(3)
[1] "1, 1"
[1] "1, 2"
[1] "1, 3"
[1] "2, 1"
[1] "2, 2"
[1] "2, 3"
[1] "3, 1"
[1] "3, 2"
[1] "3, 3"
> 

Your code only prints the numbers on the left.

CodePudding user response:

Another way to write your function is using expand.grid over l lists of sequences of length l.

f <- \(l) do.call(paste,
                  cbind(expand.grid(replicate(l - 1, seq.int(l), simplify=FALSE)), 
                        sep=', '))
f(3)
# [1] "1, 1" "2, 1" "3, 1" "1, 2" "2, 2" "3, 2" "1, 3" "2, 3" "3, 3"

f(4)
#  [1] "1, 1, 1" "2, 1, 1" "3, 1, 1" "4, 1, 1" "1, 2, 1" "2, 2, 1" "3, 2, 1"
#  [8] "4, 2, 1" "1, 3, 1" "2, 3, 1" "3, 3, 1" "4, 3, 1" "1, 4, 1" "2, 4, 1"
# [15] "3, 4, 1" "4, 4, 1" "1, 1, 2" "2, 1, 2" "3, 1, 2" "4, 1, 2" "1, 2, 2"
# [22] "2, 2, 2" "3, 2, 2" "4, 2, 2" "1, 3, 2" "2, 3, 2" "3, 3, 2" "4, 3, 2"
# [29] "1, 4, 2" "2, 4, 2" "3, 4, 2" "4, 4, 2" "1, 1, 3" "2, 1, 3" "3, 1, 3"
# [36] "4, 1, 3" "1, 2, 3" "2, 2, 3" "3, 2, 3" "4, 2, 3" "1, 3, 3" "2, 3, 3"
# [43] "3, 3, 3" "4, 3, 3" "1, 4, 3" "2, 4, 3" "3, 4, 3" "4, 4, 3" "1, 1, 4"
# [50] "2, 1, 4" "3, 1, 4" "4, 1, 4" "1, 2, 4" "2, 2, 4" "3, 2, 4" "4, 2, 4"
# [57] "1, 3, 4" "2, 3, 4" "3, 3, 4" "4, 3, 4" "1, 4, 4" "2, 4, 4" "3, 4, 4"
# [64] "4, 4, 4"

Note: "R version 4.1.2 (2021-11-01)".

  • Related