rmultisampling

Multiple Random Sampling in R


I currently have a data frame called liquidation where I want to run 30 random samples of 1000 observations each from it, designate which account came from which sample and then combine it into a new data frame with all 30 samples combined:

Here is how I did it manually while using the dplyr package for random sampling but want to simplify it for repeatability:

Sample_1 <- liquidation %>%
  sample_n(1000)
Sample_1$Obs <- 1

Sample_2 <- liquidation %>%
  sample_n(1000)
Sample_2$Obs <- 2

Sample_3 <- liquidation %>%
  sample_n(1000)
Sample_3$Obs <- 3
....
Sample_30 <- liquidation %>%
  sample_n(1000)
Sample_30$Obs <- 30

Then I combine it all into a single combined data frame:

Combined <- rbind(Sample_1, Sample_2,   Sample_3,   Sample_4,   Sample_5,   Sample_6,   Sample_7,   Sample_8,   Sample_9,   Sample_10,  
                  Sample_11,    Sample_12,  Sample_13,  Sample_14,  Sample_15,  Sample_16,  Sample_17,  Sample_18,  Sample_19,  
                  Sample_20,    Sample_21,  Sample_22,  Sample_23,  Sample_24,  Sample_25,  Sample_26,  Sample_27,  Sample_28,  
                  Sample_29,    Sample_30)

str(Combined)
'data.frame':   30000 obs. of  31 variables:

Solution

  • Here's an example using mtcars (selecting 5 rows at random, 10 times)

    Combined <- bind_rows(replicate(10, mtcars %>% sample_n(5), simplify=F), .id="Obs")
    

    We use the base function replicate() to repeat the sampling multiple times. Then we use dplyr's bind_rows() to merge the samples and keep track of the which sample they came from.