I am working with the following dataset:
dataFrame <- read.table(header=T, text='Students Year Score Flag
1 0 62 0
1 1 66 0
1 2 62 0
1 3 73 0
2 0 70 0
2 1 50 0
2 2 50 0
2 3 70 0
3 0 68 0
3 1 74 0
3 2 68 0
3 3 78 0
4 0 50 0
4 1 50 0
4 2 50 0
4 3 58 0
5 0 63 0
5 1 63 0
5 2 67 0
5 3 70 0
6 0 63 0
6 1 63 0
6 2 63 0
6 3 69 0
7 0 62 0
7 1 63 0
7 2 64 0
7 3 65 0
8 0 67 0
8 1 73 0
8 2 65 0
8 3 75 0
9 0 54 1
9 1 63 1
9 2 50 1
9 3 49 1
9 3 50 1
10 0 60 1
10 1 81 1
10 2 50 1
10 3 49 1')
In the dataset above I have the following variables:
"Students": factor with 10 levels (1,2,...,10)
"Year": factor with 4 levels (0,1,2,3)
The dependent variable "Score"
and a variable "Flag" that idenfies students that had at least 1 "Score" below 50 in the Year 3
In this data set the only two students "Flag" = 1 are the "Student" = 9 and "Student" = 10.
What I would like to achieve is a balanced partition of the data set that takes into account both the variable "Flag" and the variable "Students". For instance in this data set this means to have the "Student" 9 in one partition and the 10 in the other, for instance:
training
Students Year Score Flag
1 0 62 0
1 1 66 0
1 2 62 0
1 3 73 0
2 0 70 0
2 1 50 0
2 2 50 0
2 3 70 0
3 0 68 0
3 1 74 0
3 2 68 0
3 3 78 0
4 0 50 0
4 1 50 0
4 2 50 0
4 3 58 0
6 0 63 0
6 1 63 0
6 2 63 0
6 3 69 0
10 0 60 1
10 1 81 1
10 2 50 1
10 3 49 1
test
Students Year Score Flag
5 0 63 0
5 1 63 0
5 2 67 0
5 3 70 0
6 0 63 0
6 1 63 0
6 2 63 0
6 3 69 0
7 0 62 0
7 1 63 0
7 2 64 0
7 3 65 0
8 0 67 0
8 1 73 0
8 2 65 0
8 3 75 0
9 0 54 1
9 1 63 1
9 2 50 1
9 3 49 1
9 3 50 1
I have tried the following but doesn't seem to work
library(caret)
trainIndex <- createDataPartition( c( dataFrame$Flag , dataFrame$Students ) ,
p = .6 ,
list = FALSE ,
times = 1 )
dataFrame[ trainIndex , ]
dataFrame[ -trainIndex , ]
What would be the best way of obtaning what I need?
Many thanks