title: Stratified Split for Test and Train set
body: <p>I'm using this dataset, but instead of random sampling, I think stratified sampling would be better because the binary outcome variable consists of 90% == 1 and 10% == 0. So this code below works, but it's with random sampling</p>
  
  <pre><code>x = model.matrix(BirthWeightOz ~., ncbirths )
  y = as.vector(ncbirths$BirthWeightOz)
  
  x[,c(3,4,8,10)] &lt;- scale(x[,c(3,4,8,10)]) # non-factor variabelen omzetten naar z-scores
  x&lt;- x[,-1] # verwijderen van de kolom intercept
  
  set.seed(1)
  train &lt;- sample(1:nrow(x), nrow(x)*0.8)   # random sampling train set van 80%
  test &lt;- (1:nrow(x))[-train]  #  testset van 20%
  y.test = y[test]
  y.train = y[train]
  
  
  
  # 10-fold cross validation for ridge regression
  result.ridge.cv &lt;- cv.glmnet(x[train,], y[train], alpha = 0,lambda = 10^seq(-2, 5, length.out = 50), nfolds = 10)
  print(result.ridge.cv$lambda.min) # Best cross validated lambda
  print(result.ridge.cv$lambda.1se) # Conservative est. of best lambda (1 stdev)
  
  ## To plot Root Mean Squared Error (RMSE) to be on the same scale as y_train_ncb:
  result.ridge.cv$cvm &lt;- result.ridge.cv$cvm^0.5
  result.ridge.cv$cvup &lt;- result.ridge.cv$cvup^0.5
  result.ridge.cv$cvlo &lt;- result.ridge.cv$cvlo^0.5
  plot(result.ridge.cv, ylab = "Root Mean-Squared Error")
  print(c(result.ridge.cv$lambda.min, result.ridge.cv$lambda.1se))
  
  result.ridge.best &lt;- glmnet(x[train,], y[train], alpha = 0, lambda = result.ridge.cv$lambda.1se,standardize = TRUE, intercept = TRUE)
  result.ridge.best$beta
  
  ridge.pred = predict(result.ridge.best, newx = x[test,])
  ridge.pred_train = predict(result.ridge.best, newx = x[train,])
  ridge_mse_test &lt;- mean((ridge.pred-y.test)^2)
  ridge_mse_train &lt;- mean((ridge.pred_train-y.train)^2)
  # MSE voor de train set = 217.77 en voor de test set 217.912
  </code></pre>
  
  <p>If I try something like this: `then the rest of the code starting from 10 fold cross-validation doesn't work very well. Can you help me out how to stratified sample, but still is a vector.</p>
  
  <pre><code>train.index &lt;- createDataPartition(ncbirths$BirthWeightOz, p = .8, list = FALSE)
  train &lt;- ncbirths[ train.index,]
  test  &lt;- ncbirths[-train.index,]
  y.train = as.vector(ncb_train$BirthWeightOz)
  y.test = as.vector(ncb_test$BirthWeightOz)
  ``
  </code></pre>