How to split train/test data 50% by class and grouping by Object ID in R? I get pixel values ​​from it using reference polygons. Extracted pixel values are in data frame, but one row represent extracted values for single pixel. In the classification I need to split the dataset into test (50%) and training (50%) by class (tree, meadow e.t.c)

I know how to split a set according to classes. However, I want values ​​extracted for one polygon to be assigned to one of the sets (training OR test ) and they were not mixed

For this purpose I want to use the polygon ID (Object Identification).
I would like to do this using the createDataPartition function. These are just two sample classes (there are many more)

Here is part of table with extracted values:

"band_1"    "band_2"    "band_3"    "CLASS" "Id"
110 134 119 "tree"  1
112 133 118 "tree"  1
105 125 110 "tree"  2
112 132 117 "tree"  2
109 125 115 "meadow"    6
93  110 101 "meadow"    6
86  106 95  "meadow"    7
105 136 116 "meadow"    7
102 128 111 "meadow"    8
108 129 115 "meadow"    8
113 134 119 "meadow"    8


Here is code:

trainIndeks &lt;- caret::createDataPartition(EXTRACTED$CLASS, p = 0.5, list=FALSE, times = 1)

    dataTrain &lt;- EXTRACTED[trainIndeks,]
    dataTest &lt;- EXTRACTED[-trainIndeks,]
Instead of:

dataTrain &lt;- EXTRACTED[trainIndeks,]
dataTest &lt;- EXTRACTED[-trainIndeks,]


try:

dataTrain &lt;- EXTRACTED[ID %% 2 == 1,]
dataTest  &lt;- EXTRACTED[ID %% 2 == 0,]


dataTrain will contain only odd ID, dataTest only even ones.

Using this method you may lose the balance of CLASS distribution between dataTrain and dataTest, but you may improve it by replication or removing of a few records, or by checking the distribution in other splitting, e.g.

dataTrain &lt;- EXTRACTED[ID %% 4 &lt; 2,]
dataTest  &lt;- EXTRACTED[ID %% 4 &gt; 1,]


EDIT:

For random changing the split, you can use:

set.seed(123)
N &lt;- 10
#N &lt;- round(max(EXTRACTED$ID)/10) # for more random grouping
p &lt;- 0.5 # train/(train+test) ratio
idx &lt;- sample(0:(N-1),round(N*p))
dataTrain &lt;- EXTRACTED[ID %% N %in% idx,]
dataTest  &lt;- EXTRACTED[!(ID %% N %in% idx),]