Generate same random sample each time in loop using sample_frac

Viewed 70

How can I generate same random sample each time in loop using sample_frac

library(dplyr)

tbl = tibble(val = 1:50)

for (i in 1:3)
{
   tbl_sample = tbl %>% sample_frac(0.1)
   print(tbl_sample)
}
2 Answers

Create a list and then assign it to the list element by looping over the sequence - print only prints the output to the console

n <- 3
lst1 <- vector('list', n)
for(i in seq_len(n)) {
    lst1[[i]] <- tbl %>%
       sample_frac(0.1)
}

If we want to get 5 random indices

for(i in seq_len(n)) {
    lst1[[i]] <- tbl %>%
     mutate(rn = row_number()) %>%
     slice_sample(prop = 0.1)
}

In addition this can be automatically done with replicate

lst1 <- replicate(n, tbl %>% 
                   sample_frac(0.1), simplify = FALSE)

We can use purrr, and loop through 1:3 with the same expression as the .fn argument:

library(purrr)
library(dplyr)

map(1:3, ~{
        tbl_sample = tbl %>% sample_frac(0.1)
        head(tbl_sample)
})

[[1]]
# A tibble: 5 x 1
    val
  <int>
1     1
2    20
3    35
4    32
5    19

[[2]]
# A tibble: 5 x 1
    val
  <int>
1    45
2    24
3    42
4    46
5    10

[[3]]
# A tibble: 5 x 1
    val
  <int>
1    35
2    23
3    28
4    49
5    43

You may want every sample in a single column in a dataframe. For that we may use imap_dfc:

imap_dfc(1:3, ~{
        tbl %>% sample_frac(0.1) %>% head %>% set_names(paste0('sample_', .y))
})

# A tibble: 5 x 3
  sample_1 sample_2 sample_3
     <int>    <int>    <int>
1       49       17        8
2       29        9        6
3       25       35       50
4        9        4       44
5       34       45        3
> 
Related