dplyr , mutate, make a random number

Hi, there. This is my issue.

I want to input a random number by a group.

For instance,
if alc == grp1, then a value of a new variable, named 'alc_annual' , has to be random number between 24 and 36.

R code >
    tmp <- tmp %>% 
      mutate(annual_alc = case_when(alc == 1 ~ 0 ,
                                    alc == 2 ~ 0 ,
                                    alc == 4 ~ 12,
                                    alc == 5 ~ runif(6876,24,36)[i],
                                    alc == 6 ~ runif(6876,48,56)[i],
                                    alc == 7 ~ runif(6876,104,156)[i],
                                    alc == 8 ~ runif(6876,330,366)[],
                                    TRUE ~ annual_alc))

But the problem is that when I run the above code, the whole data which 'alc==4' are input a same number.

I just need to make a different random number although they are in the same group.

I'll waiting for some advices and thanks for your considering.

Hi, maybe something like this?

# test dataset
tmp <- tibble(alc = sample(seq(1:10), 6876, replace = TRUE),
              annual_alc = sample(seq(20:100), 6876, replace = TRUE)) %>%
  mutate(rand5 = runif(6876,24,36),
         rand6 = runif(6876,48,56),
         rand7 = runif(6876,104,156),
         rand8 = runif(6876,330,366))

# output
tmp %>%
  mutate(annual_alc = case_when(alc == 1 ~ 0 ,
                                alc == 2 ~ 0 ,
                                alc == 4 ~ 12,
                                alc == 5 ~ rand5,
                                alc == 6 ~ rand6,
                                alc == 7 ~ rand7,
                                alc == 8 ~ rand8,
                                TRUE ~ as.numeric(annual_alc))) %>% 
  select(-(rand5:rand8))

# A tibble: 6,876 x 2
     alc annual_alc
   <int>      <dbl>
 1     2        0  
 2     1        0  
 3     6       49.7
 4     5       34.9
 5     2        0  
 6     2        0  
 7     9       38  
 8     4       12  
 9     5       27.7
10     5       29.1
# ... with 6,866 more rows

if you use group_by(row_number) runif will run for each row individually:

require(dplyr)


a <- mtcars %>% 
  group_by(row_number()) %>% 
  mutate(rand_num = case_when(cyl == 4 ~ runif(1,24,36),
            cyl == 6 ~ runif(1,48,56),
            cyl == 8 ~ runif(1,330,366),
            TRUE ~ 1))
1 Like

Oh, Thanks!
I now solve the problem.

1 Like

Thanks for your consideration.!! :slight_smile: :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.