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)
>
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 if
statement to a file and source
it (or pipe it into R) you will get the error on the else
branch.
But the following will work just fine:
if (exp) a <- 1 else a <- 2
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:
f <- function (exp)
if (exp)
a <- 1
else
a <- 2
In R you can define functions without braces around the body. But the above code will fail for the same reason that the standalone if
without braces fails. By contrast, if I had written the if
on 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:
f <- function (exp) {
if (exp)
1
else
2
}
… and the same when using if
inside the shell:
a <- if (exp) 1 else 2
because in R, if
is an expression which returns a value.