如何将数据随机分成三个相等的大小? [英] How to randomly split data into three equal sizes?

查看:135
本文介绍了如何将数据随机分成三个相等的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含来自三个不同项目的9558行.我想将此数据集随机分为三个相等的组,并为每个组分配一个唯一的ID,以使Project1_Project_2_Project3变为Project1Project2Project3.

I have a dataset with 9558 rows from three different projects. I want to randomly split this dataset in three equal groups and assign a unique ID for each group, so that Project1_Project_2_Project3 becomes Project1, Project2 and Project3.

我尝试了很多事情,并从与我有类似问题的人那里搜索了代码.我曾经使用过sample_n()sample_frac(),但是不幸的是我自己无法解决此问题:/

I have tried many things, and googled codes from people with similar problem as I have. I have used sample_n() and sample_frac(), but unfortunately I can't solve this issue myself :/

我制作了一个数据集示例,如下所示:

I have made an example of my dataset looking like this:

ProjectName <- c("Project1_Project2_Project3")
data <- data.frame(replicate(10,sample(0:1,9558,rep=TRUE)))
data <- data.frame(ProjectName, data)

然后应将输出随机分为三个相等的组nrow=3186,然后分配给值

And the output should be randomly split in three equal group of nrow=3186 and then assigned to the values

ProjectName Count of rows
Project1     3186
Project2     3186
Project3     3186

推荐答案

IMO,仅分配随机项目名称就足够了.

IMO it should be sufficient to assign just random project names.

dat$ProjectName <- sample(factor(rep(1:3, length.out=nrow(dat)), 
                          labels=paste0("Project", 1:3)))

结果

Result

head(dat)
#   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 ProjectName
# 1  1  1  0  1  1  1  1  0  1   0    Project1
# 2  1  1  1  1  1  1  0  0  1   0    Project1
# 3  0  0  1  1  0  0  0  1  1   1    Project1
# 4  1  1  1  0  1  0  1  1  0   1    Project3
# 5  1  0  0  1  1  1  1  0  0   1    Project1
# 6  1  0  0  0  0  1  0  1  1   1    Project3

table(dat$ProjectName)
# Project1 Project2 Project3 
#     3186     3186     3186 

数据

Data

set.seed(42)
dat <- data.frame(replicate(10, sample(0:1, 9558, rep=TRUE)))

这篇关于如何将数据随机分成三个相等的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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