Herd formation in animal populations, for example to escape a predator or coordinate feeding, is a widespread phenomenon. Understanding which interactions between individual animals are important for generating such emergent self-organisation has been a key focus of ecological and mathematical research. Here we show the relationship between the algorithmic rules of herd-forming agents, and the mathematical structure of the corresponding spatial-moment dynamics. This entails scaling up from the rules of individual, herd generating behaviour to the macroscopic dynamics of herd structure. The model employs a mechanism for neighbour-dependent, directionally-biased movement to explore how individual interactions generate aggregation and repulsion in groups of animals. Our results show that a combination of mutually attractive and repulsive interactions with different spatial scales is sufficient to lead to the stable formation of groups with a characteristic size.