Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run two indices in r

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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,

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading