Earth is depleted in volatile elements relative to chondritic meteorites, its possible building blocks. The extent of this depletion increases with decreasing condensation temperature, and is approximated by a cumulative normal distribution, unlike that in any chondrite. However, moderately volatile elements, occupying the mid-range of the distribution, have chondritic isotope ratios, contrary to that expected from loss by partial vaporisation/condensation. Here we reconcile these observations by showing, using N-body simulations, that Earth accreted stochastically from many precursor bodies whose variable compositions reflect the temperatures at which they formed. Impact-induced atmospheric loss was efficient only when the proto-Earth was small, and elements that accreted thereafter retain near-chondritic isotope ratios. Earth's composition is reproduced when initial temperatures of planetesimal-to embryo-sized bodies are set by disk accretion rates of (1.08±0.17)×10 -7 solar masses/yr, although they may be perturbed by 26 Al heating on bodies formed at different times. The model implies a heliocentric gradient in composition and rapid planetesimal formation within ~1 Myr, in accord with radiometric volatile depletion ages of Earth.