R: Is there a function like at_exit in the Ruby? - r

I want do something before exit the R program, just like in the Ruby we can do:
at_exit do
print "before exit"
end
The on.exit in R, will do something before exit current function, but cannot work for whole program.
I've searched online, but cannot find useful info.

According to hrbrmstr's advice, I've tried .Last and reg.finalizer and they work. This is the summary:
Using .Last variable
.Last <- function() {
cat("at last\n")
}
cat("ok\n")
The result will be:
[1] "ok"
at last
Using reg.finalizer function
reg.finalizer(environment(),
function(e) cat("at last\n"),
onexit=TRUE)
The result will be:
NULL
[1] "ok"
at last

Related

Weird Behaviour in R if else Statement

I'm quit new to R programming. While I was trying to write my first if else statement I came across a weird behaviour which I don't understand.
When I run below code:
x = 4;
y=4;
if (x==y) {
print('they are equal');
} else {
print('they are not equal');
}
I get no error and I get the expected output. However when I change the indentation of the same exact code as below:
if(x==y){print('they are equal');}
else{print('they are not equal');}
I get an error message saying that 'Error: unexpected 'else' in "else"'.
So does this means that R is an indentation sensitive language like Python?
To my limited experience, in R syntex, else statement should start from the same line where if statement ends. Otherwise, it won't work. And R is NOT indenting sensitive. For example,
This will work
if(x==y){print('they are equal')
} else
{print('they are not equal')}
[1] "they are equal"
Even this will work
if(x==y){print('they are equal')} else
{print('they are not equal')}
[1] "they are equal"
This will also work
if(x==y){print('they are equal')} else {print('they are not equal')}
[1] "they are equal"
But the code you have written doesn't work because else statement doesn't start from the same line where if statement ends. Another example would be,
This won't work
if(x==y){print('they are equal')}
else {
print('they are not equal')}
Also, you don't need the semi-colons.

How to tell if any tests failed from result of testthat::test_dir

I have a small testing program that uses testthat
library(testthat)
source("src/MyFile.r")
results <- test_dir("tests", reporter="summary")
So, I am running this via Rscript. The problem is that the exit code is always 0 even when there were test failures. So, I want to call stop if there are any failures. But I can't seem to get the right bit of code to do that. Is there a method or field in results that I should be looking at to determine if there were any errors?
You could also tweak jamesatha's answer to retrieve the number of test failures.
failed.tests <- sapply(results, function(r) {
!is(r$result[[1]], "expectation_success")
})
You then allows you to fail, as before:
if (any(failed.tests)) {
stop("There were test failures")
}
or do something more bespoke like
if (any(failed.tests)) {
failed.test.count <- length(which(failed.tests))
stop(paste(failed.test.count,"failed tests is",failed.test.count,"too many!")
}
Currently, my solution is iterating through the results like this:
for (i in 1:length(results)) {
if (!is(results[[i]]$result[[1]], "expectation_success")) {
stop("There were test failures")
}
}
You can simply pass stop_on_failure=TRUE in as a parameter to test_dir. If you get any test failures it will raise an error and exit non zero.
e.g:
results <- test_dir("mypath", stop_on_failure=TRUE)
This is documented here

Using audio_play_sound() in a if statement GameMaker

I am trying to use the command:
audio_play_sound()
I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.
if (key_jump) && (jumps > 0)
{
jumps -=1;
vsp = -jumpspeed;
}
Code that causes problem:
if (key_jump) && (jumps > 0)
{
jumps -=1;
vsp = -jumpspeed;
audio_play_sound(snd_jump)
}
Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance
The problem is stated in the error, you're providing the wrong number of arguments to the audo_play_sound function.
from the docs
audio_play_sound(index, priority, loop);
As the person above states your answer is audio_play_sound(snd_jump, 1, false).

print text when calling a model

I hope this is not a double post. I've been looking for an answer.
I have a function that returns a rather big list. So i would like it to print some text in between all the results of the list. A bit as you know it from lm and other models.
Consider this R script
y<-function(z)
{
l<-list()
print("hello world")
l$answer<-2*z
return(l)
}
x<-y(5)
This is a small example. I tried a solution with print but this is a bad solution , simply because it executes print when i save the variable as x<-fun(5). I just want it to execute text when you ask it explicit, or even better,if you can construct your own "summary" command to a list.
Thanks for your time.
If I understood what you want to do , I think you are looking to implement the S3method print.
set the class attribute :"someclass" of the y function return value
define print.someclass
here the code:
y<-function(z)
{
l<-list()
l$answer<-2*z
## Roland comment : usually better to preserve existing classes:
class(l) <- c('someclass', class(l))
return(l)
}
print.someclass<-
function(x,...){ ## add here what you want to print
print("hello world")
}
x<-y(5)
Now when you type x at console or print(x):
x
[1] "hello world"

how do you know which functions in R are flagged for debugging?

I've been using debug() more often now, but sometimes I wonder which functions have been flagged for debugging. I know that you can use isdebugged() to find out if a particular function is flagged. But is there a way for R to list all the functions that are being debugged?
This is convoluted, but it works:
find.debugged.functions <- function(environments=search()) {
r <- do.call("rbind", lapply(environments, function(environment.name) {
return(do.call("rbind", lapply(ls(environment.name), function(x) {
if(is.function(get(x))) {
is.d <- try(isdebugged(get(x)))
if(!(class(is.d)=="try-error")) {
return(data.frame(function.name=x, debugged=is.d))
} else { return(NULL) }
}
})))
}))
return(r)
}
You can run it across all your environments like so:
find.debugged.functions()
Or just in your ".GlobalEnv" with this:
> find.debugged.functions(1)
function.name debugged
1 find.debugged.functions FALSE
2 test TRUE
Here I created a test function which I am debugging.
Unless you wanted to get into something like writing a function to fire everything through isdebugged(), I don't think you can.
In debug.c, the function do_debug is what checks for the DEBUG flag being set on an object. There are only three R functions which call the do_debug C call: debug, undebug and isdebugged.
which(sapply(lsf.str(), isdebugged))

Resources