在R中创建唯一的随机组ID [英] Create unique random group id in R

查看:105
本文介绍了在R中创建唯一的随机组ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个唯一的,随机分配的(无替换)组ID,而不使用for循环。据我所知:

I am trying to create a unique, randomly assigned (without replacement) group id without using a for loop. This is as far as I got:

library(datasets)
library(dplyr)

data(iris)

iris <- iris  %>% group_by(Species) %>% mutate(id = cur_group_id())

这给我每个虹膜$种的组ID,但是,我希望组ID是从c(1,2,3)随机分配的,而不是分配的根据数据集的顺序。

This gives me a group id for each iris$Species, however, I would like the group id to randomly assigned from c(1,2,3) as opposed to assigned based on the order of the dataset.

任何帮助创建该对象的方法都将非常有帮助!我相信有办法用dplyr做到这一点,但我很困惑...

Any help creating this would be very helpful! I am sure there is a way to do this with dplyr but I am stumped...

推荐答案

也许您可以玩一些技巧在 group_by 上通过添加 sample 操作,例如

Maybe you can play some tricks on group_by by adding sample operation, e.g.,

iris <- iris %>%
  group_by(factor(Species, levels = sample(levels(Species)))) %>%
  mutate(id = cur_group_id())

这篇关于在R中创建唯一的随机组ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆