Take random sample by group

This is available as the slice_sample function in dplyr:

library(dplyr)
new_df <- df %>% group_by(ID) %>% slice_sample(n=500)

In older versions of R, the function was called sample_n, which has been deprecated.

Leave a Comment