It's doesn't happen organically. It is usually designed by city planners (or equivalent functions depending on the city). It makes most sense to have mixture of residential and commercial buildings in the same area so that there is no foot traffic vacuum depending on the time of the day. Foot traffic vacuum creates space for potential crimes.
(e.g, if you separate commercial and residential, the commercial area will be more likely crime ridden at night and residential area will be more prone to crime during the day).