1

In the following simplified example when I ask for the value of the variable "var" by writing just "var" I receive nothing. I have to use the print function in order this to work. Can someone explain this behavior to me, please. Thank you in advance all of you.

Foo <- function(){
    var <- 1
    var         # it does nothing
    print(var)  # 1
}

Foo()

On the hand it works fine if we just write, out of any function:

var <- 2
var        # 2
print(var) # 2
Apostolos Polymeros
  • 823
  • 1
  • 8
  • 19
  • Yes, you need either `print` or `cat` to return "var", as you clearly showed. –  Jun 12 '15 at 05:27
  • I think you are right. There I see a comment "This is one of those quirks in R". I shall wait a little bit and then I shall withdraw the question. Thank you a lot Pascal. – Apostolos Polymeros Jun 12 '15 at 05:45
  • 1
    @Pascal, The two topics are definitely connected but not really the same, so I think this question is valid. The issue in the other question is why assignments do not produce return values, whereas this question is about why statements do not get printed. Perhaps the answers to the other questions satisfied the OP, but I don't think there is any harm in leaving this one open too. – Backlin Jun 12 '15 at 06:48

1 Answers1

1

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.

Backlin
  • 14,612
  • 2
  • 49
  • 81