Anand Rayudu
Anand Rayudu

Reputation: 39

apply function - custom function returning NULL at the end

x = matrix(1:5)

func = function(x)  {
   for ( i in 1:x ) {
       print(i)
   }
}

apply(X=x, 1, func)

Output :

[1] 1
[1] 1
[1] 2
[1] 1
[1] 2
[1] 3
[1] 1
[1] 2
[1] 3
[1] 4
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
NULL

Why is this function generating NULL at the end ?

Upvotes: 3

Views: 158

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226087

By definition, an R function returns the result of the last expression to be evaluated. In this case, the expression is the entire for loop, which returns NULL. If you want to not print the null result, you can store the result in a variable (result <- apply(...)) or use invisible():

invisible(apply(X=x, 1, func))

I don't know of a way to modify the function itself to get this behaviour, since you are calling the function through apply().

By the way, why not invisible(lapply(x,func)) ?

Upvotes: 6

Related Questions