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
lipid <-as.data.frame(cer_data[,c(7:9)])
dim(lipid)
for (i in 1:length(lipid)) {
variable <- lipid[,i]
lme_cer <- lme(variable ~ factor(Remission) + Time + Age + BMI + SEX, random = ~1 | Lacal.Patient.ID, method = "REML", data = cer_data)
print(summary(lme_cer)$tTable)
}
Thank you all for the amazing help!
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.
Without knowing your data, conceptually it should be sth like that
df <- data.frame(lipid = rep(c(LETTERS[1:4]), each = 4), x1 = c(rnorm(16, 10, 1)), x2 = c(rnorm(16, 20, 5) ))
df
for (i in levels(df$lipid)){
print(paste("MODEL", i, sep = ""))
df1 = subset(df, lipid == i)
model <- lm(x1~x2, data = df1 )
print(summary(model)$coef)
}