Quantcast
Viewing all articles
Browse latest Browse all 1015

An R function return and assignment puzzle

By John Mount

Here is an R programming puzzle. What does the following code snippet actually do? And ever harder: what does it mean? (See here for some material on the difference between what code does and what code means.)

f 

In R version 3.2.3 (2015-12-10) -- "Wooden Christmas-Tree" the code appears to call the function f() and return nothing (nothing is printed). When teaching I often state that you should explicitly use a non-assignment expression as your return value. You should write code such as the following:

f 

(We are showing an R output as being prefixed with ##.)

But take a look at the this:

f 

It prints! Read further for what is really going on.

What is going on is: in R in the absence of an explicit return() statement functions always return the value of the last statement executed. Also in R assignment is itself a value returning expression (returning the value assigned). So the original function f is in fact returning a 5. We just don't see it. The 5 returned is “invisible” (see the “return values” section of Advanced R, Hadley Wickham, CRC 2015 for details).

As we said: R assignments return values. So you can return them and you can chain them like so:

a 

What happens is the assignment x returns a value (in this case 5), but that value has an attribute marking it invisible. This is why when you assign a value to a variable in R you don't see printing as a side effect. For example we don't see anything printed when we type the following:

x 

We can remove the invisible attribute by adding parenthesis as follows:

( x 

Assignment also strips the invisible attribute, so we can write code like the following:

f 

(We can ...read more

Source:: r-bloggers.com


Viewing all articles
Browse latest Browse all 1015

Trending Articles