Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers for groups R

I want to generate the same random number for groups. Unfortunately, my following code generates random number for each row.

randomised <- data %>%
  group_by(`ID`)%>%
  mutate(random = sample(1:100,n(), replace = TRUE))

Any help is appreciated.

like image 500
goegges Avatar asked Nov 15 '25 04:11

goegges


1 Answers

You should just select 1 value from sample which will be recycled for all the values in the group.

library(dplyr)
data %>% group_by(ID)%>% mutate(random = sample(100,1))

Or in base R :

data$random <- with(data, ave(seq_along(ID), ID,FUN = function(x) sample(100, 1)))
like image 145
Ronak Shah Avatar answered Nov 17 '25 18:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!