title: Cross-validating a logistic regression in R
body: <p>I am running a logistic regression a binary DV with two predictors (gender, political leaning: binary, continuous). I need help getting my GLMs to run in a cross-validation! I can't my code to work despite reclassifying the variables multiple times. I'm not sure what's going on.</p>
  
  <p>Here is the code I have: </p>
  
  <pre><code>`
  
  #######################################################
  #     Cross-Validation of the Logistic Regression
  #######################################################
  
  
  gen &lt;- as.numeric(choicelife.data$gender)
  lnc &lt;- as.numeric(choicelife.data$lc)
  procprol &lt;-as.numeric(choicelife.data$views)
  
  # This code could be useful
  nCV &lt;- 50
  MSE_1 &lt;- numeric(nCV)
  MSE_2 &lt;- numeric(nCV)
  
  folds &lt;- cut(sample(n),breaks=nCV,labels=FALSE)
  
  #Perform n.folds fold cross validation
  i &lt;- 1
  for(i in 1:nCV){
  
    #Segement your data by fold using the which() function 
    testIndexes &lt;- which(folds==i,arr.ind=TRUE)
    testData &lt;- choicelife.data[testIndexes, ]
    trainData &lt;- choicelife.data[-testIndexes, ]
  
    # Models
    mod1&lt;- glm(views ~ gen,
               family=binomial(link=logit), data=trainData)
  
    mod2&lt;- glm(views ~ gen + lnc,
               family=binomial(link=logit), data=trainData)
  
    # Get predictions
    pred_1 &lt;- predict(mod1, newdata = testData)
    pred_2 &lt;- predict(mod2, newdata = testData)
  
    # Calculate MSE
    MSE_1[i] &lt;- mean((testData$views - pred_1)^2)
    MSE_2[i] &lt;- mean((testData$views - pred_2)^2)
  }
  warnings()
  
  # mean MSEs
  mean(MSE_1) 
  mean(MSE_2) 
  
  # get differences
  diffs &lt;- MSE_1 - MSE_2
  
  # get 95% CIs
  meandiff &lt;- mean(diffs) 
  sddiff &lt;- sd(diffs) 
  c(meandiff-2*sddiff, meandiff+2*sddiff) # 95% Confidence interval (n, n)
  </code></pre>
  
  <pre><code>
  </code></pre>