简体   繁体   中英

How to set different set.seed() per group and then sample()

I would like to sample any number from Min to Max column of a data.frame after grouping and every group having different seed. I've tried a few approaches, you can see them in the reproducible example below, but none of them work.
The data.frame consists of four columns:

letters - my grouping variable
seed - an integer that is dynamic and group/letter specific
min - minimum value for the sample()
max - maximum value for the sample()

Here is a reproducible example:

set.seed(123)
data.frame(letter = sample(letters[1:3],20, replace=TRUE)) %>% 
  group_by(letter) %>% 
  summarise(seed = n()) %>% 
  mutate(min = ifelse(letter == "a", 20,
                      ifelse(letter == "b", 40, 60)),
         max = ifelse(letter == "a", 30,
                      ifelse(letter == "b", 50, 70)))  %>%

  group_by(letter) %>%
  # set.seed(seed) %>%  # or mutate(randomNumber = sample(min:max, 1, set.seed(seed))) # these aren't working, but I hope you get my point 
  mutate(randomNumber = sample(min:max, 1))


Many thanks in advance!

I would suggest to use pmap from the purrr package in your last row:

library(tidyverse)

set.seed(123)
data.frame(letter = sample(letters[1:3],20, replace=TRUE)) %>% 
  group_by(letter) %>% 
  summarise(seed = n()) %>% 
  mutate(min = ifelse(letter == "a", 20,
                      ifelse(letter == "b", 40, 60)),
         max = ifelse(letter == "a", 30,
                      ifelse(letter == "b", 50, 70)))  %>%

  group_by(letter) %>%
  mutate(randomNumber = pmap_dbl(list(min, max, seed), function(x, y, z){set.seed(z); sample(x:y, 1)}))


# A tibble: 3 x 5
# Groups:   letter [3]
  letter  seed   min   max randomNumber
  <fct>  <int> <dbl> <dbl>        <dbl>
1 a          5    20    30           21
2 b          7    40    50           49
3 c          8    60    70           63

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM