This quote from Shakespeare's Hamlet means: even when actions seem crazy or chaotic, there is a deliberate plan or purpose behind them.
In context, Hamlet acknowledges his strange behavior but explains it's a calculated act to avenge his father's murder. The phrase now describes any seemingly irrational behavior that actually has a hidden rationale.