Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply function - custom function returning NULL at the end

Tags:

r

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 ?

like image 641
Anand Rayudu Avatar asked Feb 19 '26 09:02

Anand Rayudu


1 Answers

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)) ?

like image 93
Ben Bolker Avatar answered Feb 22 '26 00:02

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!