Home > Mobile >  What's wrong with the break in for loop in R?
What's wrong with the break in for loop in R?

Time:01-17

I have a code:

nc=10
for(n in 1:n){
  mergeCells(wb, 1, cols = (4*n):(4*n 3), rows = 1:1)
  if ((4*n)>nc) {break
  }
}

However it produces an error:

  Merge intersects with existing merged cells: 
        L1:Q1.
Remove existing merge first.

I do have some merged cells in L1:Q1. However the error shouldn't have occured since I specified the loop to break once 4n > nc (where nc=10). When n=3, 4n> nc and the loop should break. The 10th cell is J1, not L1, so the merged cells shouldn't overlap.

CodePudding user response:

for the third iteration of the loop, the code tries to merge L1:O1: (n <- 3; LETTERS[(4*n):(4*n 3)]), and this occurs before the break line. Swapping the order of the lines in the loop should fix it:

nc=10
for(n in 1:n){    ##should this be for(n in n:nc)
  if ((4*n)>nc) {break}
  mergeCells(wb, 1, cols = (4*n):(4*n 3), rows = 1:1)
}

Obviously without the dataset wb it isn't possible to check.

  • Related