简体   繁体   中英

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.

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)))

data.table一个选项:

setDT(data)[, random := sample(100, 1), ID]

Not sure why we need this, if we are trying to anonymise the IDs ( cyl column in mtcars example data), then this is pretty random to me:

library(dplyr)

mtcars %>% 
  mutate(random = as.integer(as.factor(cyl)))

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