'Print Function Inside of Apply Function Producing Unexpected Results
Could anyone explain why including a print() function within an apply() function produces (in my opinion) unexpected results.
Using a toy example, if you were to return a value, the apply() function works as expected:
apply(matrix(1:8, ncol = 2), 1, function(x) return(1))
[1] 1 1 1 1
However, if you attempt to print the same value, here's the result:
apply(matrix(1:8, ncol = 2), 1, function(x) print(1))
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1 1 1 1
What is going on under the hood that causes the apply() function to yield such a result when printing?
Solution 1:[1]
I'm not sure what you would expect the behaviour to be, but from the documentation, print prints a value and returns it invisibly. So you're getting the side effect of the printed value as well as the collected results from returning 1 for each row of your matrix.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | George Savva |
