0
votes

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.

1
Did you mean print(paste("done at", y))? Although you'd see the output of paste("done at", y) when you type that in console, however, you would not see the output in a loop.Suren
Oh! that's interesting. Wrapping it with print worked. Wonder why i did not think of it :) Thank you for the explanation on its functionality in loop.Naga Pakalapati

1 Answers

2
votes

I think what you are looking for is cat(). Try

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

If you want to switch to a new line in the output you have to add "\n", e.g.:

cat("not done\n")