When I look at R functions I often find the following structure:
f <- function(exp=T) {
if (exp)
a <- 1
else
a <- 2
}
f()
f(F)
This will run without error. But executing the inner function code throws an error as R probably assumes that the statement is finished after the first assignment a <- 1 and cannot handle the following else.
exp=T
if (exp)
a <- 1
else
a <- 2
Now, this makes sense to me, but I still would like to understand why the behaviour of the executed code differs when executed inside or outside a function.
It’s a consequence of using an interactive shell (REPL) to run scripts:
After the first branch the shell has seen a complete statement so it assumes that you’re done typing. Unfortunately, R uses the same shell for interpreting scripts even if they are not typed in interactively – so even when you save the
ifstatement to a file andsourceit (or pipe it into R) you will get the error on theelsebranch.But the following will work just fine:
Here, the interpreter swallows the line and executes it.
In your function one would assume that the same applies – and it does! However, the function itself starts with an open brace in your case, so R has to read until it finds the matching closing brace. By contrast, take this function declaration:
In R you can define functions without braces around the body. But the above code will fail for the same reason that the standalone
ifwithout braces fails. By contrast, if I had written theifon a single line this code would once again work.Incidentally, your function uses an assignment to a variable that isn’t used. You can (should) do the following instead:
… and the same when using
ifinside the shell:because in R,
ifis an expression which returns a value.