I believe the answer is that R doesn't print the outcome of a statements occurring inside functions simply because that could lead to a lot of mess when running other people's code.
You might want to do stuff like
f <- function(x){
na.fail(x)
rowMeans(x)
}
where na.fail
is a function that stops the execution if x
contains missing values and returns x
if not. Printing out x
is most likely not what the author intended or what the user wants, so the R developers probably reckoned that it is better to require the author of the function to explicitly state what should be printed.
You could of course argue that the above example is just poor coding and that you should do this instead:
f <- function(x) rowMeans(na.fail(x))
Nevertheless, the default behaviour of R is probably the most defensive solution.
However, if a function returns a value on the last line
Foo <- function(){
var <- 1
print("var")
var # it doesn't show var
print("print(var)")
var # It shows var
}
it does get printed when evaluated on the top level of the R session (even without print!), i.e. if it was called explicitly by the user
Foo()
[1] "var"
[1] "print(var)"
[1] 1
This is because Foo()
is a statement of its own, returning a value that get printed if it exists on the top level. If it occurs inside a function however, it doesn't get printed.
f <- function(x){
Foo()
rowMeans(x)
}
Except if it get passed back up to the top.