We propose a theory of social interactions based on self-selection and comparative advantage. In our model, students choose peer groups based on their comparative advantage within a social environment. The eﬀect of moving a student into a diﬀerent environment with higher-achieving peers depends on where in the ability distribution she falls and the shadow prices that clear the social market. We show that the model’s key prediction—an individual’s ordinal rank predicts her behavior and test scores—is borne out in one randomized controlled trial in Kenya as well as administrative data from the U.S. To test whether our selection mechanism can explain the eﬀect of rank on outcomes, we conduct an experiment with nearly 600 public school students in Houston. The experimental results suggest that social interactions are mediated by self-selection based on comparative advantage.