sampling

Take n random elements from a List<E>?

别来无恙 提交于 2019-11-26 07:29:57
问题 How can I take n random elements from an ArrayList<E> ? Ideally, I\'d like to be able to make successive calls to the take() method to get another x elements, without replacement. 回答1: 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

Stratified random sampling from data frame

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 01:56:13
I have a data frame in the format: head(subset) # ants 0 1 1 0 1 # age 1 2 2 1 3 # lc 1 1 0 1 0 I need to create new data frame with random samples according to age and lc. For example I want 30 samples from age:1 and lc:1, 30 samples from age:1 and lc:0 etc. I did look at random sampling method like; newdata <- function(subset, age, 30) But it is not the code that I want. 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 =

Stratified random sampling from data frame

点点圈 提交于 2019-11-26 01:49:41
问题 I have a data frame in the format: head(subset) # ants 0 1 1 0 1 # age 1 2 2 1 3 # lc 1 1 0 1 0 I need to create new data frame with random samples according to age and lc. For example I want 30 samples from age:1 and lc:1, 30 samples from age:1 and lc:0 etc. I did look at random sampling method like; newdata <- function(subset, age, 30) But it is not the code that I want. 回答1: I would suggest using either stratified from my "splitstackshape" package, or sample_n from the "dplyr" package: ##