How to prevent running i=j in double for loops in R?

Viewed 51

I want to prevent running the i=j case and substitute it as NA in R. Here I prepared a small example. When i=j, I have the output 0. But I want to print it as NA. How can I do this one? Thanks.

n = 5
for(j in 1:(n-1)){
  for(i in 0:(n-2)){
    print(2^(abs(i-j)))
  }
}

The outputs are 2, 1, 2, 4,....

4 Answers

Either if (i==j) { print(NA) } else { ... } or if (i==j) {print(NA); break}

Why don't you use if statement?

n = 5
for(j in 1:(n-1)){
  for(i in 0:(n-2)){
    if(i == j){
      print(NA)
    } else{
      print(2^(abs(i-j)))
      
    }
  }
}

Just for fun here is a vectorized version that might be much more efficient, depending on the size of n. It returns a vector, which you could print line by line if that is your desired output. The idea is to generate the pairings from the nested loop using expand.grid, then subtracting these vectors from each other and setting the cases where i==j (i.e. the difference being 0) to NA.

2^abs({
    rd <- do.call(`-`, asplit(expand.grid(j=0:(n-2), i=1:(n-1)), 2))
    rd[rd==0] <- NA; rd})

You can try ifelse or if ... else .... Below is one option with ifelse:

n <- 5
for (j in 1:(n - 1)) {
  for (i in 0:(n - 2)) {
    print(ifelse(i == j, NA, 2^(abs(i - j))))
  }
}

giving

[1] 2
[1] NA
[1] 2
[1] 4
[1] 4
[1] 2
[1] NA
[1] 2
[1] 8
[1] 4
[1] 2
[1] NA
[1] 16
[1] 8
[1] 4
[1] 2

Another option is using NA^(i==j) as a mask, e.g.,

n <- 5
for (j in 1:(n - 1)) {
  for (i in 0:(n - 2)) {
    print(2^(abs(i - j)) * NA^(i == j))
  }
}
Related