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
A blind answer, assuming that your dependent variables are organized in columns and not in rows (as I think they are).
The main difference between my approach and your approach is that I loop over the names of the lipids rather than their position in the data set. This allows me (a) to construct a temporary data set in a less error-prone way, and (b) to construct a temporary formula for the fixed-effects part of your model.
The lme function is then applied to the temporary data set with the temporary formula, and the result is saved in a list for easier access.
# names of lipids
lipid.names <- colnames(cer_data)[1:881]
no.lipids <- length(lipid.names)
# create a named list to hold the fitted models
fitlist <- as.list(1:no.lipids)
names(fitlist) <- lipid.names
# loop over lipid names
for(i in lipid.names){
# print status
print(paste("Running entity:", i, "which is", which(lipid.names==i), "out of", no.lipids))
# create temporary data matrix and model formula
tmp <- cer_data[, c(i,"Remission","Time","Age","BMI","SEX","Local.Patient.ID")]
fml <- as.formula( paste( i, "~", paste(c("Remission","Time","Age","BMI","SEX"), collapse="+") ) )
# assign fit to list by name
fitlist[[i]] <- lme(fml, random=~1|Lacal.Patient.ID, method="REML", data=tmp)
}
In my opinion it's easiest to work with temporary objects that exactly contain what is needed at that iteration of the loop.
Note that I cannot check this solution for errors because you haven't supplied a reproducible example: Here's how.