R without return value

I helped my friend with some of his code. I did not know how to explain the strange behavior, but I could tell him that its functions obviously did not return anything. Here is a minimal reproducible example:

derp <- function(arg){
  arg <- arg+3
}

data <- derp(500)
data
#[1] 503
derp(500)
#nothing outputs
class(derp(500))
#[1] "numeric"

Is there a name for this that I can google for? Why is this happening? Why is the arg argument not destroyed after the derp () call completes?

+4
source share
4 answers

You need to understand the difference between a function returning a value and printing that value. By default, the function returns the value of the last evaluated expression, which in this case is an assignment

arg <- arg + 3

( , R - , , .) data <- derp(500) data, 503.

, . R. , :

derp <- function(arg)
{
    arg <- arg + 3
    arg
}

derp <- function(arg)
arg + 3
+6

arg. R , , return.

arg . :

alwaysReturnSomething = function()
{
  x = runif(1)
  if(x<0.5) 20  else 10
}
> for(x in 1:10) cat(alwaysReturnSomething())
20202020102010101020

alwaysReturnSomething <- function(){}
> z=alwaysReturnSomething()
> z
NULL
+1

, , <<-,

derp <- function(arg){
  arg <- arg+3
  b<<-3
}

Try and call b

0
source

This is a curious behavior.

Basically, derp()it returns if you assign an output derp(), and derp()does not return if you do not assign a result. This is because the assignment ( <-) function returns using the invisible () function. see Make the function return without sound for how it works.

You can see the same behavior with derp2:

derp2 <- function(arg) {
  invisible(arg + 3)
}
derp2(3)
# nothing
b <- derp2(3)
b
# 6
0
source

Source: https://habr.com/ru/post/1525144/


All Articles