Note that there are some explanatory texts on larger screens.

plurals
  1. POTraining and test set with respect to group affiliation
    primarykey
    data
    text
    <p>I’m using the following function in R to split subjects/samples into training and test set and it works really fine. However, in my dataset the subjects are divided into 2 groups (Patients and control subjects) and therefore, I wish to split the data while maintaining the proportions of patients and control subjects in each training and test set at the same ratio as in the complete data set. How can I do that in R? How can I modify the following function so that it will take into account group affiliation as it split the data into training and test set?</p> <pre><code># splitdf function will return a list of training and testing sets# splitdf &lt;- function(dataframe, seed=NULL) { if (!is.null(seed)) set.seed(seed) index &lt;- 1:nrow(dataframe) trainindex &lt;- sample(index, trunc(length(index)/2)) trainset &lt;- dataframe[trainindex, ] testset &lt;- dataframe[-trainindex, ] list(trainset=trainset,testset=testset) } # apply the function splits &lt;- splitdf(Data, seed=808) # it returns a list - two data frames called trainset and testset str(splits) # there are "n" observations in each data frame lapply(splits,nrow) # view the first few columns in each data frame lapply(splits,head) # save the training and testing sets as data frames training &lt;- splits$trainset testing &lt;- splits$testset` </code></pre> # <p>Example: use the built in iris data and split the dataset into training and testing sets. This dataset has 150 samples and has a factor called Species consisting of 3 levels (setosa, versicolor and virginica)</p> <h3>load the iris data</h3> <p><code>data(iris)</code></p> <h3>splits the dataset into training and testing sets:</h3> <p><code>splits &lt;- splitdf(iris, seed=808)</code></p> <pre><code>str(splits) lapply(splits,nrow) lapply(splits,head) training &lt;- splits$trainset testing &lt;- splits$testset </code></pre> <p>As you can see here, the function “splitdf” does not take into account group affiliation “Species” when it splits the data into training and test set and as the result the number samples with respect to setosa, versicolor and virginica in the training and test set are Not proportional to that of the main dataset. So, How can I modify the function so that it will take into account group affiliation as it split the data into training and test set?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload