2

I have the following R code:

n <- 100
simul <- function() {
  x <- sample(c(-1, 1), n, replace = TRUE)
  s <- cumsum(c(0, x))
}
(tmp = simul())

In the above code, simul() returns a vector to tmp. How is this possible, since the function simul() does not define any return value (at least, explicitly)?

halfer
  • 19,824
  • 17
  • 99
  • 186
The Pointer
  • 2,226
  • 7
  • 22
  • 50
  • 1
    you are assigning `<-` or `=` to an identifier and here the `.Last.value` from 's' is passed on to it – akrun Oct 20 '19 at 17:39
  • 1
    Ahh, I see. What is `.Last.Value`? Is there any documentation that explains this (I haven't encountered any mention of this)? – The Pointer Oct 20 '19 at 17:40
  • 1
    You can test it by adding one more line `s1 <- 'hello'` at the end of the function and see what happens. The `.Last.value` i meant is the last line of code evaluated – akrun Oct 20 '19 at 17:41
  • Tried it and it was as you said. Is this mentioned in the r documentation? – The Pointer Oct 20 '19 at 17:43
  • @akrun That question doesn't really address the same point in a direct and clear way. – The Pointer Oct 20 '19 at 17:48
  • I guess the question is similar to the one you mentioned. If I quote the answer `By default, a function returns the value of the last expression evaluated,`. What do you expect as an answer here? – akrun Oct 20 '19 at 17:48
  • 1
    From https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/function : *If the end of a function is reached without calling `return`, the value of the last evaluated expression is returned.* – The Pointer Oct 20 '19 at 17:51
  • 1
    @akrun yes, I understand now. Thank you for the clarification. – The Pointer Oct 20 '19 at 17:52

0 Answers0