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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With