title: Making a loop for lme() in r
body: <p>I am trying to use lme function from nlme package inside a for loop. I have tried (almost) everything now, but without any luck. Without the loop my lme function are working fine. I have 681 different lipids to analyse, so i need the loop.</p>
  
  <p>Bonus info:</p>
  
  <ul>
  <li>I have used str() and my data has the same lengths before the loop</li>
  </ul>
  
  <p>A simplified version of my data look like this: </p>
  
  <p><code>&gt;dput(head("ex.lme(loop)"))
  structure(list(Lacal.Patient.ID = c(12L, 12L, 12L, 13L, 13L, 
  13L), Time = c(0L, 1L, 3L, 0L, 1L, 3L), Remission = c(0L, 0L, 1L, 0L, 0L, 1L), Age = c(46L, 43L, 36L, 47L, 34L, 45L), SEX = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("f", "m"), class = "factor"), BMI = c(25L, 26L, 23L, 27L, 26L, 27L), Sph = c(0.412, 1.713, 
      1.48, 0.735, 1.025, 1.275), S1P = c(2.412, 3.713, 3.48, 2.735, 
      3.025, 3.275), Cer..C16. = c(1.4472, 2.2278, 2.088, 1.641, 
      1.815, 1.965)), .Names = c("Lacal.Patient.ID", "Time", "Remission", "Age", 
  "SEX", "BMI", "Sph", "S1P", "Cer..C16."), row.names = c(NA, 6L
  ), class = "data.frame")</code></p>
  
  <p>Here is what i do i R:</p>
  
  <p><code>library(nlme)
      attach(cer_data)
      Remission &lt;- factor(Remission)
      Time &lt;- factor(Time)
      SEX &lt;- factor(SEX)</code></p>
  
  <h1>How I think the loop should look like:</h1>
  
  <pre><code>lipid &lt;-as.matrix(cer_data[,c(7:9)]) # my lipids a at row 7-9in my data 
  beg &lt;- 1
  end &lt;- nrow(lipid)
  dim(lipid)
  for (i in beg:end) { 
    print(paste("Running entity: ", colnames(lipid)[i], " which is ",i, " out of", end))
    variable &lt;- as.numeric(lipid[i])
    lme_cer &lt;- lme(variable ~ Remission + Time + Age + BMI + SEX, random = ~1|Lacal.Patient.ID, method = "REML", data = cer_data)
  }
  </code></pre>
  
  <blockquote>
    <p>Error : Error in model.frame.default(formula = ~variable + Remission + Time +  : variable lengths differ (found for 'Remission’)</p>
  </blockquote>
  
  <h1>Without the loop my analysis are working fine (Lipid(x) is just one of the lipids) :</h1>
  
  <pre><code>lme_cer &lt;- lme(lipid(x) ~ Remission + Time + Age + BMI + SEX , random = ~1 | Lacal.Patient.ID, method = "REML", data = cer_data)
  summary(lme_cer)
  </code></pre>
  
  <p>Can anyone see the problem with my loop? I am not used to programming or using R, so there is probably some stupid mistakes. </p>