R: Function changing print behavior when returning NULL

Viewed 123

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?

1 Answers

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)

Related