Skip to content
Prev 389080 / 398506 Next

Splitting a data column randomly into 3 groups

Hi Bert and All: good morning

I promise this would be the last time to write about this topic.

I come up with this R function (please see below), for sure with your help.
It works for all sample sizes. I also provided three different simple
examples.

with many thanks
abou

##################    Here it is    ###############

Random.Sample.IDs <- function (N,n, ngroups){    #### N = population size,
and n = sample size, ngroups = number of groups

population.IDs <- seq(1, N, by = 1)
sample.IDs <- sample(population.IDs,n)

##### to print sample.IDs in a column format
##### --------------------------------------------------
sample.IDs.in.column<-data.frame(sample.IDs)
print(sample.IDs.in.column)

reminder.n<-n%%ngroups
reminder.n

n.final<-n-reminder.n
n.final

  m <- n %/% 3
  m
  s <- sample(1:n, n)

if (reminder.n == 0) {

  group1.IDs <- sample.IDs[s[1:m]]
  group2.IDs <- sample.IDs[s[(m+1):(2*m)]]
  group3.IDs <- sample.IDs[s[(m*2+1):(3*m)]]

} else if(reminder.n == 1){

  group1.IDs <- sample.IDs[s[1:(m+1)]]
  group2.IDs <- sample.IDs[s[(m+2):(2*m+1)]]
  group3.IDs <- sample.IDs[s[(m*2+2):(3*m+1)]]

} else if(reminder.n == 2){

  group1.IDs <- sample.IDs[s[1:(m+1)]]
  group2.IDs <- sample.IDs[s[(m+2):(2*m+2)]]
  group3.IDs <- sample.IDs[s[(m*2+3):(3*m+2)]]
}
nn<-max(length(group1.IDs),length(group2.IDs),length(group3.IDs))
nn
length(group1.IDs) <- nn
length(group2.IDs) <- nn
length(group3.IDs) <- nn

groups.IDs <-cbind(group1.IDs,group2.IDs,group3.IDs)

groups.IDs

}


#####  Examples
#####  --------

Random.Sample.IDs (100,12,3)    #### group sizes are equal (n1=n2=n3=4)

Random.Sample.IDs (100,13,3)    #### group sizes are NOT equal (n1=5, n2=4,
n3=4)

Random.Sample.IDs (100,17,3)    #### group sizes are NOT equal (n1=6, n2=6,
n3=5)


______________________


*AbouEl-Makarim Aboueissa, PhD*

*Professor, Statistics and Data Science*
*Graduate Coordinator*

*Department of Mathematics and Statistics*
*University of Southern Maine*
On Sun, Sep 5, 2021 at 6:50 PM Bert Gunter <bgunter.4567 at gmail.com> wrote: