Cannot break Shrek loop in Rstudio - r

I have created a "while" loop that looks like this:
x <- 2
while (x < 8) {
print("Shrek")
}
Now, I have tried breaking the loop by inserting break in to the while loop, like this:
while (x < 8) {
print("Shrek")
break
}
but this doesn't break the loop, the console just keeps printing "Shrek".
How can i make it stop? Have I put break in the wrong place?
Side question: Can there arise any problems from exiting Rstudio while it's in an on-going while() loop like this?
Thanks!
Edit:
Pressing escape stopped the loop. Is there any line of code in the console that also stops it?

Based on the code you have given I can't reproduce this. When I run everything, break works just fine. Have you potentially defined a variable called 'break' that would have overridden the default function? If not try resetting R and running this again.

Related

Julia print statement not working in certain cases

I've written a prime-generating function generatePrimes (full code here) that takes input bound::Int64 and returns a Vector{Int64} of all primes up to bound. After the function definition, I have the following code:
println("Generating primes...")
println("Last prime: ", generatePrimes(10^7)[end])
println("Primes generated.")
which prints, unexpectedly,
Generating primes...
9999991
Primes generated.
This output misses the "Last prime: " segment of the second print statement. The output does work as expected for smaller inputs; any input at least up to 10^6, but somehow fails for 10^7. I've tried several workarounds for this (e.g. assigning the returned value or converting it to a string before calling it in a print statement, combining the print statements, et cetera) and discovered some other weird behaviour: if the "Last prime", is removed from the second print statement, for input 10^7, the last prime doesn't print at all and all I get is a blank line between the first and third print statements. These issues are probably related, and I can't seem to find anything online about why some print statements wouldn't work in Julia.
Thanks so much for any clarification!
Edit: Per DNF's suggestion, following are some reductions to this issue:
Removing the first and last print statements doesn't change anything -- a blank line is always printed in the case I outlined and each of the cases below.
println(generatePrimes(10^7)[end]) # output: empty line
Calling the function and storing the last index in a variable before calling println doesn't change anything either; the cases below work exactly the same either way.
lastPrime::Int = generatePrimes(10^7)[end]
println(lastPrime) # output: empty line
If I call the function in whatever form immediately before a println, an empty line is printed regardless of what's inside the println.
lastPrime::Int = generatePrimes(10^7)[end]
println("This doesn't print") # output: empty line
println("This does print") # output: This does print
If I call the function (or print the pre-generated-and-stored function result) inside a println, anything before the function call (that's also inside the println) isn't printed. The 9999991 and anything else there may be after the function call is printed only if there is something else inside the println before the function call.
# Example 1
println(generatePrimes(10^7)[end]) # output: empty line
# Example 2
println("This first part doesn't print", generatePrimes(10^7)[end]) # output: 9999991
# Example 3
println("This first part doesn't print", generatePrimes(10^7)[end], " prints") # output: 9999991 prints
# Example 4
println(generatePrimes(10^7)[end], "prime doesn't print") # output: prime doesn't print
I could probably list twenty different variations of this same thing, but that probably wouldn't make things any clearer. In every single case version of this issue I've seen so far, the issue only manifests if there's that function call somewhere; println prints large integers just fine. That said, please let me know if anyone feels like they need more info. Thanks so much!
Most likely you are running this code from Atom Juno which recently has some issues with buffering standard output (already reported by others and I also sometimes have this problem).
One thing you can try to do is to flush your standard output
flush(stdout)
Like with any unstable bug restarting Atom Juno also seems to help.
I had the same issue. For me, changing the terminal renderer (File -> Settings -> Packages -> julia-client -> Terminal Options) from webgl to canvas (see pic below) seems to solve the issue.
change terminal renderer
I've also encountered this problem many times. (First time, it was triggered after using the debugger. It is probably unrelated but I have been using Julia+Juno for 2 weeks prior to this issue.)
In my case, the code before the println statement needed to have multiple dictionary assignation (with new keys) in order to trigger the behavior.
I also confirmed that the same code ran in Command Prompt (with same Julia interpreter) prints fine. Any hints about how to further investigate this will be appreciated.
I temporarily solve this issue by printing to stderr, thinking that this stream has more stringent flush mechanism: println(stderr, "hello!")

Manually interrupt a loop in R and continue below

I have a loop in R that does very time-consuming calculations. I can set a max-iterations variable to make sure it doesn't continue forever (e.g. if it is not converging), and gracefully return meaningful output.
But sometimes the iterations could be stopped way before max-iterations is reached. Anyone who has an idea about how to give the user the opportunity to interrupt a loop - without having to wait for user input after each iteration? Preferably something that works in RStudio on all platforms.
I cannot find a function that listens for keystrokes or similar user input without halting until something is done by the user. Another solution would be to listen for a global variable change. But I don't see how I could change such a variable value when a script is running.
The best idea I can come up with is to make another script that creates a file that the first script checks for the existence of, and then breaks if it is there. But that is indeed an ugly hack.
Inspired by Edo's reply, here is an example of what I want to do:
test.it<-function(t) {
a <- 0
for(i in 1:10){
a <- a + 1
Sys.sleep(t)
}
print(a)
}
test.it(1)
As you see, when I interrupt by hitting the read button in RStudio, I break out of the whole function, not just the loop.
Also inspired by Edo's response I discovered the withRestarts function, but I don't think it catches interrupts.
I tried to create a loop as you described it.
a <- 0
for(i in 1:10){
a <- a + 1
Sys.sleep(1)
if(i == 5) break
}
print(a)
If you let it go till the end, a will be equal to 5, because of the break.
If you stop it manually by clicking on the STOP SIGN on the Rstudio Console, you get a lower number.
So it actually works as you would like.
If you want a better answer, you should post a reproducible example of your code.
EDIT
Based on the edit you posted... Try with this.
It's a trycatch solution that returns the last available a value
test_it <- function(t) {
a <- 0
tryCatch(
for(i in 1:10){
a <- a + 1
message("I'm at ", i)
Sys.sleep(t)
if(i==5) break
},
interrupt = function(e){a}
)
a
}
test_it(1)
If you stop it by clicking the Stop Sign, it returns the last value a is equal to.

Pause a loop using RStudio IDE

I want to pause and continue a loop.
Does rstudio have some options that can pause a loop and continue the loop?
Just like "stop" button can stop the loop.
I don't know if the readline() function can help:
a <- 0
for(i in 1:4) {
a <- a + i
if(readline() == "0") break
}
Now you have to insert values for each iteration.
For instance, if you want to stop at iteration 2:
1
0
> a
[1] 3
Maybe this solution does not totally meet your requirements (I haven't really understood your question), but it may help you have a control of each iteration in order to decide if and when to stop it.
to continue you can use
next
and to go out from loop you can use
break
see here for more details.

Error with using if else inside function

I have problem in using if else inside function, my code is like this:
ConvertWgtZooLS <- function(WgtZoo, LSWay, Pos){
If(LSWay == 0){
NewWgtZoo <- WgtZoo
}else{
BackPos <- BackMatrix(Pos,1)
NewWgtZoo<- Ifelse((Sign(WgtZoo) * Sign(BackPos) * LSWay)>=0, WgtZoo, 0)
}
return(NewWgtZoo)
}
However, when I run that in R, error message appears as:
"Error: unexpected '{' in:
"ConvertWgtZooLS <- function(WgtZoo, LSWay, Pos){
If(LSWay == 0){"
How can I resolve this? What is the syntax problem there? I checked many websites and seems the above if else syntax is correct.
Thanks a lot!
The error in your code is that you have used If instead of if, and R is case-sensitive. Thus, it is possible to have another function named If that does something different from if, and, as #danielkullmann points out, that function is exactly what R is looking for.
The error messages that R produces are not always the most helpful, but in this case, it does point you very close to the problem area. It shows you where it got "confused" but it's up to you to figure out why!
After you've fixed that first problem, you'll find another one (for the same reason) on line 6, where you have written Ifelse instead of ifelse.
One last point: R is pretty whitespace friendly, so it is good practice to leave some space in your code to help improve legibility, particularly with if and else statements. Here's why:
I find if (LSWay == 0) { easier to read than if(LSWay == 0){
When using an actual function, like sum(x), you do not usually add a space, making it easier to spot these conditional statements in large blocks of code.
The Google R Style Guide is an interesting read in this regard.

Print j on every outside loop iteration in R

For the following code: I can't figure out why j does not print on every outside loop iteration.
x = 0
for (j in 1:15)
{
for (i in 1:100000)
{
x = x + 1
}
print(j)
}
What R seems to be doing is running the the whole thing, and at the end print out all the js, not one by one as when every loop iterates.
It seems to be that j should be printing after every loop iteration, what am I missing here?
Is there a way to make it such that j in printed on every outside loop iteration?
Thank You
I'm guessing you are using the Windows Rgui, which buffers its console output, and then writes it out in chunks (see the R Windows FAQ 7.1). To force immediate printing to the console, you can simply add a call to flush.console() after the print() statement.
x = 0
for (j in 1:15) {
for (i in 1:100000) {
x = x + 1
}
print(j)
flush.console()
}
R output is typically buffered. You can circumvent this in two ways. Either (only on Windows, IIRC) you can go to the menu of the R Gui, and chose Misc -> Buffered Output (or press Ctrl-W) to disable buffering (which typically slows down execution), or you can call flush.console() any time you want to ensure that the output is actually shown (e.g. to show progress).
Not familiar with R but that code looks right for what you are trying to do. May be something to do with output buffering as I've come accross the same issue in PHP where the whole script runs before any output is rendered.

Resources