

Return values by default

Suppose you forgot to add return(result) in the addPercent() function. What would happen then? You can find out if you delete the last line of the addPercent() function, save the file, and source it again to load it into the workspace.

Any change you make to a function will take effect only after you send the adapted code to the console. This will effectively overwrite the old function object by a new one.

If you try addPercent(new.numbers) again, you see . . . nothing. Apparently, the function doesn’t do anything anymore — but this is an illusion, as you can see with the following code:

> print( addPercent(new.numbers) )
 [1] "82.2%" "2.5%" "162%" "40%"

In this case, the last line of the function returns the value of result invisibly, which is why you see it only if you specifically ask to print it. The value is returned invisibly due to the assignment in the last line. Because this isn’t really practical, you can drop the assignment in the last line and change the function code to the following:

addPercent <- function(x){

This function works again as before. It may look like return() is utterly useless, but you really need it if you want to exit the function before the end of the code in the body. For example, you could add a line to the addPercent function that checks whether x is numeric, and if not, returns NULL, like this:

addPercent <- function(x){
 if( !is.numeric(x) ) return(NULL)

Break the walls

The braces, {}, form the proverbial wall around the function, but in some cases you can drop them as well. Suppose you want to calculate the odds from a proportion. The odds of something happening is no more than the chance it happens divided by the chance it doesn’t happen. So, to calculate the odds, you can write a function like this:

> odds <- function(x) x / (1-x)

Even without the braces or return() statement, this works perfectly fine, as you can see in the following example:

> odds(0.8)
[1] 4

If a function consists of only one line of code, you can just add that line after the argument list without enclosing it in braces. R will see the code after the argument list as the body of the function.

You could do the same with the addPercent() function by nesting everything like this:

> addPercent <- function(x) paste(round(x * 100, digits = 1), "%", sep = "")

That’s a cunning plan to give the next person reading that code a major headache. It’s a bit less of a cunning plan if that next person is you, though, and chances are, it will be.

Saving space in a function body is far less important than keeping the code readable, because saving space gains you nothing. Constructs like the odds function are useful only in very specific cases.