I am using the nlme
package to learn multilevel models, and following examples from the textbook "Discovering Statistics Using R" when it happened.
The data set is Honeymoon Period.dat
, also downloadable under their companion website.
require(nlme)
require(reshape2)
satisfactionData = read.delim("Honeymoon Period.dat", header = TRUE)
restructuredData<-melt(satisfactionData, id = c("Person", "Gender"), measured = c("Satisfaction_Base", "Satisfaction_6_Months", "Satisfaction_12_Months", "Satisfaction_18_Months"))
names(restructuredData)<-c("Person", "Gender", "Time", "Life_Satisfaction")
#print(restructuredData)
#restructuredData.sorted<-restructuredData[order(Person),]
intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)
randomIntercept <-lme(Life_Satisfaction ~1, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt="optim"))
anova(intercept, randomIntercept)
timeRI<-update(randomIntercept, .~. + Time)
timeRS<-update(timeRI, random = ~Time|Person)
ARModel<-update(timeRS, correlation = corAR1(0, form = ~Time|Person))
The error occured at this moment, when I am trying to update "timeRS" model. The error message is as follows:
Error in as.character.factor(X[[i]], ...) : malformed factor
Any stats people/programmers here who knows what this means?
I have looked at this book. It appears that the coding is wrong. The error you are getting is because your time variable is a factor and you need it to be numeric. In the author's first figure in the book he represents time as numeric (0 - 3) but his code for the models is incorrect. I've recoded it for you:
The anova read out for model comparisons is now exactly as shown in the book.