Take n random elements from a List?

Two main ways. Use Random#nextInt(int): List<Foo> list = createItSomehow(); Random random = new Random(); Foo foo = list.get(random.nextInt(list.size())); It’s however not guaranteed that successive n calls returns unique elements. Use Collections#shuffle(): List<Foo> list = createItSomehow(); Collections.shuffle(list); Foo foo = list.get(0); It enables you to get n unique elements by an incremented index (assuming that the … Read more

Stratified random sampling from data frame

I would suggest using either stratified from my “splitstackshape” package, or sample_n from the “dplyr” package: ## Sample data set.seed(1) n <- 1e4 d <- data.table(age = sample(1:5, n, T), lc = rbinom(n, 1 , .5), ants = rbinom(n, 1, .7)) # table(d$age, d$lc) For stratified, you basically specify the dataset, the stratifying columns, and … Read more