Animal behaviors often are decomposable into discrete, stereotyped elements, well separated in time. In one model, such behaviors are triggered by specific commands; in the extreme case, the discreteness of behavior is traced to the discreteness of action potentials in the individual command neurons. Here, we use the crawling behavior of the nematode Caenorhabditis elegans to demonstrate the opposite view, in which discreteness, stereotypy, and long timescales emerge from the collective dynamics of the behavior itself. In previous work, we found that as C. elegans crawls, its body moves through a "shape space" in which four dimensions capture approximately 95% of the variance in body shape. Here we show that stochastic dynamics within this shape space predicts transitions between attractors corresponding to abrupt reversals in crawling direction. With no free parameters, our inferred stochastic dynamical system generates reversal timescales and stereotyped trajectories in close agreement with experimental observations. We use the stochastic dynamics to show that the noise amplitude decreases systematically with increasing time away from food, resulting in longer bouts of forward crawling and suggesting that worms can use noise to modify their locomotory behavior.