Syntax for nested for loop in R when j is a function of i

Viewed 163

What I want to do would be as follows in C#:

for (int i = 1; i <= 44; i++)
{
     for (int j = i + 1; j <= 44; j++)
     {
         System.Diagnostics.Debug.WriteLine(i + " " + j);
     }
}

This produces 1,...,44 then 2,...44 etc.

I tried to replicate this in R via:

for (i in 1:44) for (j in i+1:44) print(paste(i, " ", j))

Results are completely wrong. I would appreciate if someone could explain to me how to emulate the results I get in C# in R - I find the syntax in R very unintuitive.

Thanks in advance.

2 Answers

I've tried both solutions presented in the comments, and neither seems to do exactly what you want. In any case, here's a simple approach:

for(i in 1:5){
  for(j in i:5){
    cat(c(i,j), "\n")
  }
}

1 1 
1 2 
1 3 
1 4 
1 5 
2 2 
2 3 
2 4 
2 5 
3 3 
3 4 
3 5 
4 4 
4 5 
5 5 

And since you're new to R's syntax, this is essentially saying that you'll update the lower bound/index on j as i. So start with i=1, tick up j 1-5, then move to i=2, and tick up j 2-5, etc. That all said, I don't know C#, so I can't be certain if this is exactly what you want.

I don't speak C# but I have some serious doubts that the code produces what you claim it does. However, my answer below can be adjusted easily.

We don't like loops for this kind of tasks. An R-way of doing this would look more like this:

n <- 5
M <- combn(0:n, 2)
M[1,] <- M[1,] + 1
t(M)
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    2
# [3,]    1    3
# [4,]    1    4
# [5,]    1    5
# [6,]    2    2
# [7,]    2    3
# [8,]    2    4
# [9,]    2    5
#[10,]    3    3
#[11,]    3    4
#[12,]    3    5
#[13,]    4    4
#[14,]    4    5
#[15,]    5    5

You can pass a function to combn if the goal is to use these as indices for some calculations.

Related