简体   繁体   English

为组 R 生成随机数

[英]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.您应该只从sample选择 1 个值,该值将被循环用于组中的所有值。

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

Or in base R :或者在基数 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:不知道为什么我们需要这个,如果我们试图匿名化 ID( mtcars示例数据中的cyl列),那么这对我来说是非常随机的:

library(dplyr)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM