Based on my understanding, your understanding is not perfect. The function can return a value without using the return keyword, as it returns the value of the last evaluated expression.
For example, consider the following example. It'll successfully print a named vector of 3 elements.
f1 <- function(x) {
y <- x + 1
}
f2 <- function(x) {
y <- x + 1
y
}
f3 <- function(x) {
y <- x + 1
return(y)
}
a <- f1(1)
b <- f1(1)
c <- f1(1)
print(c("a"=a, "b"=b, "c"=c))
Here's the relevant documentation:
If value is missing, NULL is returned. If it is a single expression, the value of the evaluated expression is returned. (The expression is evaluated as soon as return is called, in the evaluation frame of the function and before any on.exit expression is evaluated.)
If the end of a function is reached without calling return , the value of the last evaluated expression is returned.
Hope this helps.
To give an example closer to your example with an if block, the same logic applies. The following should create z successfully and then print out "xyz".
f <- function(x) {
if (x == "abc") {
y <- "pqr"
} else {
y <- "xyz"
}
}
z <- f("def")
print(z)