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 ?
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)) ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With