R equivalent of Python 'pass' statement - r

Python has a pass statement, a null operation, which can be a useful placeholder before code is complete, for example in Python:
def example_function():
pass
# stuff to do here
Is there an equivalent in R? Thank you.

Just have an empty function body:
foo = function(){
}
You should probably also add a comment, and a warning maybe?
foo = function(){
# write this tomorrow
warning("You ran foo and I havent written it yet")
}
Same thing with an if expression:
if(x==1){
# do this bit later
}else{
message("x isnt 1")
}

If you don't want NULL returned,and you don't want to wrap your function call with invisible(), you can include invisible() inside of the function body. This returns nothing:
my_func <- function(x){
invisible()
}
my_func(100)

Related

Function that self destructs

I read some post where Hadley made a joke about a self destructing function. I thought this would be relatively simple to implement but turns out it's not.
Here is an attempt to write a function named self_delete that is a quine and attempts to self destruct after printing its body. The idea was to search for the function's name in .GlobalEnv and delete it but that doesn't work. I would like to understand why this is the case.
self_delete<- function(){
print(body(self_delete))
rm(list=lsf.str(pattern="self_delete"))
}
Calling the above prints the following as expected but does not delete itself from .Globalenv, what am I missing? I did try with rm and ls too with no luck
self_delete()
{
print(body(self_delete))
rm(list = lsf.str(pattern = "self_delete"))
}
You forgot to set the envir argument to rm(), so it's trying to delete self_delete from the calling frame, not from globalenv().
This works:
self_delete <- function(){
print(body(self_delete))
rm("self_delete", envir = globalenv())
}

R: Function changing print behavior when returning NULL

This question is only for curiosity. My colleague and I were trying to write a function which returns NULL, but doesn't print it.
Before we found return(invisible(NULL)), I tried return({dummy<-NULL}) which works, but only once. After the first evaluation, the functions starts printing again:
test <- function() {
return({x<-NULL})
}
# no printout
test()
# with printout
test()
# with printout
test()
How does this come about?
I think this is due to some older return handling built into R. There are many return functions, withVisible, invisible, etc. When you return an assignment x<-null inside the return function it will not automatically print. If you want an assignment to print...
test <- function() {
withAutoprint(x<-NULL)
}
# with printout this time
test()
# with printout
test()
# with printout
test()
I think this just may be hard coded into the return function, maybe pulling something from this logic below, just a shot in the dark though.
Source: R Documentation
x <- 1
withVisible(x <- 1) # *$visible is FALSE
x
withVisible(x) # *$visible is TRUE
Again if we do not use an expression and simply return a variable or value inside our return function we get automatic printing. The reason I am guessing it returns on a second call has to do with the fact x was already assigned previously.
EDIT: I found this deep into the documentation on auto printing. "Whether the returned value of a top-level R expression is printed is controlled by the global boolean variable R_Visible. This is set (to true or false) on entry to all primitive and internal functions based on the eval column of the table in file src/main/names.c: the appropriate setting can be extracted by the macro PRIMPRINT."(Source)

R: Exit from the calling function

In R, is there a way to exit from the calling function and return a value? Something like return(), but from the parent function?
parent <- function(){
child()
# stuff afterward should not be executed
}
child <- function(){
returnFromParent("a message returned by parent()")
}
It seems stop() is doing something like that. What I want to do is to write a small replacement for stop() that returns the message that stop() writes to stderr.
Update after G5W's suggestion: I have a large number of checks, each resulting in a stop() if the test fails, but subsequent conditions cannot be evaluated if earlier checks fail, so the function must exit after a failing one. To do this 'properly', I would have to build up a huge if else construct, which I wanted to avoid.
Got it. I guess I was looking for something like this:
parent <- function(){
parent_killing_child()
print("do not run this")
}
parent_killing_child <- function(){
do.call(return, list("my message"), envir = sys.frame(-1))
}
parent()
Thanks for all the advices.
Disclaimer: This sounds a XY problem, printing the stop message to stdout has few to no value, if interactive it should not be a problem, if in a script just use the usual redirection 2 > &1 to write stderr messages to stdout, or maybe use sink as in answer in this question.
Now, if I understood properly what you're after I'll do something like the following to avoid too much code refactoring.
First define a function to handle errors:
my_stop <- function() {
e <- geterrmessage()
print(e)
}
Now configure the system to send errors to your function (error handler) and suppress error messages:
options(error = my_stop)
options(show.error.messages=FALSE)
Now let's test it:
f1 <- function() {
f2()
print("This should not be seen")
}
f2 <- function() {
stop("This is a child error message")
}
Output:
> f1()
[1] "Error in f2() : This is a child error message\n"
For the parent function, make a list of tests. Then loop over the tests, and return your message at the first failed test. Subsequent tests will not be executed after the first failure.
Sample code:
test1 <- function(){criteria <- T; return(ifelse(criteria,T,F))}
test2 <- function(){criteria <- F; return(ifelse(criteria,T,F))}
test3 <- function(){criteria <- T; return(ifelse(criteria,T,F))}
parent <- function() {
tests <- c('test1', 'test2', 'test3')
for (i in 1:length(tests)) {
passed <- do.call(tests[i],args = list())
#print(passed)
if (!passed){
return(paste("Testing failed on test ", i, ".", sep=''))
}
}
return('Congrats! All tests passed!')
}
parent()
Update
Kudos to #chris for their clever application of do.call() in their successful solution.
In five years since then, the R team has released the rlang package within the tidyverse, which provides the apt function rlang::return_from() in tandem with rlang::return_to().
While base::return() can only return from the current local frame,
these two functions will return from any frame on the current
evaluation stack, between the global and the currently active context.
They provide a way of performing arbitrary non-local jumps out of the
function currently under evaluation.
Solution
Thus, you can simply do
child <- function() {
rlang::return_from(
# Return from the parent context (1 frame back).
frame = rlang::caller_env(n = 1),
# Return the message text.
value = "some text returned by parent()"
)
}
where the parent is identified via rlang::caller_env().
Results
When called from a parent() function
parent <- function() {
child()
# stuff afterward should not be executed
return("text that should NOT be returned by parent()")
}
the child() function will force parental behavior like this:
parent()
#> [1] "some text returned by parent()"
Bonus
See my solution here for throwing an error from a parent (or from any arbitrary "ancestor").

Why expression after return's parenthesis is checked for lexical correctness, but is not evaluated?

Consider the following code:
a = function() {
return (23)
}
b = function() {
return (23) * 23
}
c = function() {
return (23) * someUndefinedVariable
}
All of the above runs successfully (if called) and return 23.
I assumed that R ignores everything that goes after the closing parenthesis of return, but it does not really, because this code fails during code loading:
d = function() {
return (23) something
}
My assumption is that in the latter example some lexer or parser fails. But in the former, expression is parsed as (return(23))*some (because return is treated like a function), but evaluation stops at return and therefore R does not try to find some.
Does that sounds ok? Is that the reason? Is such behavior intended? Can I enable some warnings so that interpreter tells me about such 'unreachable code'?
The failure of this code:
d = function() {
return (23) something
}
... has nothing to do with the prior code and everything to do with the inability to parse: return (23) something. Unlike the earlier misguided attempt to redefine c which had a valid/parseable function body, the d-body is incapable of being put into a functional form. The parser doesn't really stop at return(23) but rather after it tokenizes something and "realizes" that it is not a semicolon or an infix function name. So the R interpreter now has two expressions and no valid connector/separator between them.
The referenced objects inside R function bodies at the time of definition do not get evaluated or even checked for existence in the parameter list or outside the function. (R is not a compiler.)
R parses the statement before it is evaluated:
parse(text = "funky <- function(x) {
return(x) * dog
}")
returns:
expression(funky <- function(x) {
return(x) * dog
})
However,
parse(text = "funky <- function(x) {
return(x) dog
}")
returns:
Error in parse(text = "funky <- function(x) {\n return(x) dog\n}") :
<text>:2:19: unexpected symbol
1: funky <- function(x) {
2: return(x) dog
^
In the above example, even though the variable dog doesn't exist (and comes after return), R is still able to parse it as it correct code.
return is not just "treated like a function", it is a function. And anytime it's called, the code path will exit from whatever function you're in at that moment.
So that means that by the time R would have gotten to multiplying the result of return by 23, it's all over, that evaluation stops, and there are no errors or warnings to report (just like there are no warnings or errors when you return inside some if condition).
Whereas your last function simply cannot be parsed (which more or less means that the expression is put into a function tree), and so that (function) object can't be created.

call answer from a previous function

I'm trying to write a function in R that will return as its output, an one output from a previous function. The previous function returns a list of 3 different things.
So far the only way I've worked out how to do this is completely copy and paste the original function, and get it to return only one answer, but surely there is a shorter way in which to do this?
If the original function is named foo(), as in
foo <- function ( something ) {
# some code
return(list(residuals, residualssquared,tss))
}
then just do
bar <- function ( something ) {
return ( foo(something)$tss )
}
or simply use foo(something)$tss to directly access the tss component of the return value of foo(). There is really no need to wrap another function bar() around foo().

Resources