Randomizing two sets of numbers, not repeating the values within each group (R)

Asked

Viewed 45 times

5

Whereas I have these individuals on file:

ID
1
1
1
3
3
3
7
7
7

And I need to assign two sets of numbers to ID randomly (set1 - 1,2,3; set2 - 5,15,25). To do this my attempt was:

df %>%
  group_by(ID) %>%
  dplyr::mutate(set1=sample(c(1,2,3), size=n(), replace=F)) %>%
  ungroup()
  dplyr::mutate(set2=sample(c(5,15,25), size=n(), replace=F)) %>%
  ungroup ()

and I got this:

ID  set1 set2
1   1   15
3   1   25
7   1   25
1   2   5
3   2   15
7   2   5
1   3   25
3   3   5
7   3   15

but I need the bank to stay like this:

 ID  set1 set2
    1   1   15
    3   1   25
    7   1   5
    1   2   5
    3   2   15
    7   2   25
    1   3   25
    3   3   5
    7   3   15

I need the values not to be repeated within the groups, I’m having difficulty controlling two variables at the same time. I’ve tried to control using group_by(ID, set1) tbm, but I’m getting it. Any suggestions.Remembering that I need to assign these values randomly. Thank you.

1 answer

5


Data frame.:

df <- data.frame(ID = c(1, 1, 1, 3, 3, 3, 7, 7, 7))

Dyplr package:

library(dplyr)

Separating the problem into 2.

Here we create set1 grouped by ID:

df <- df %>% group_by(ID) %>%
  mutate(set1 = sample(c(1, 2, 3), size = n(), replace = F)) %>%
  arrange(set1)

Here we create set2 grouped by set1:

df <- df %>% group_by(set1) %>%
  mutate(set2 = sample(c(5, 15, 25), size = n(), replace = F))

df

Exit:

     ID  set1  set2
1     1     1    25
2     3     1    15
3     7     1     5
4     1     2    25
5     3     2     5
6     7     2    15
7     1     3     5
8     3     3    25
9     7     3    15

Browser other questions tagged

You are not signed in. Login or sign up in order to post.