mercredi 3 juillet 2019

Paste() function in loop/if seems to be not working as intended in R

I am trying to use paste() function in a loop with conditional statements but it doesn't work. Multiple print statements work fine. Is there a work around or am I doing something wrong here.

Please ignore the logic of the code. I just tried to do something reproducible to test the functionality.

Thanks for your time.

Below are the 3 scenarios i tried.

  1. Just using paste() with no other print function, there is no out put and seems like my code doesn't do anything.
  2. I just tried paste() with print() in else, which prints 1-9 and skips printing when the if condition is met.
  3. Above code if ran with paste in both if and else, works just fine.

FYI, paste() function just works fine outside loop.

  x <- 1
for (i in 1:20){
  y <-x
  if (y == 10){
    paste("done at", y)
    break
  }else if (y==20){
    print("not done")
  }else {
    x<- y+1
  }
}

  x <- 1
for (i in 1:20){
  y <-x
  if (y == 10){
    paste("done at", y)
    break
  }else if (y==20){
    print("not done")
  }else {
    print(y)
    x<- y+1
  }
}

  x <- 1
for (i in 1:20){
  y <-x
  if (y == 10){
    print("done")
    break
  }else if (y==20){
    print("not done")
  }else {
    print(y)
    x<- y+1
  }
}

Trying to understand if paste() works in loops or conditional statements.

Aucun commentaire:

Enregistrer un commentaire