我正在使用nlme
包来学习多级模型,并遵循教科书中的示例"使用R&#34发现统计数据;当它发生时。
数据集是蜜月Period.dat
,也可以在其配套网站下载。
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))
此时出现错误,当我尝试更新&#34; timeRS&#34;模型。 错误消息如下:
as.character.factor(X [[i]],...)出错:格式错误的因素
这里的任何统计人员/程序员都知道这意味着什么?
答案 0 :(得分:3)
我看过这本书。似乎编码是错误的。你得到的错误是因为你的时间变量是一个因素,你需要它是数字。在作者的第一个图中,他将时间表示为数字(0 - 3),但他的模型代码不正确。我已经为你记录了它:
## First, Time needs to be recoded as a numeric
restructuredData$Time.Numeric <- with(restructuredData, ifelse(Time == "Satisfaction_Base", 0,
ifelse(Time == "Satisfaction_6_Months", 1,
ifelse(Time == "Satisfaction_12_Months", 2,
ifelse(Time == "Satisfaction_18_Months", 3, NA)))))
## Baseline Model
intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)
summary(intercept)
## Model where intercept can vary for Individuals
randomIntercept <- lme(Life_Satisfaction ~ 1, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))
summary(randomIntercept)
## Add time as a fixed effect
timeRI <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))
summary(timeRI)
## Add a random slope to the model by nesting the Individual within the test time
timeRS <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~Time.Numeric|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))
summary(timeRS)
## Modeling the covariance structure structure of the errors with a first-order autoregressive covariance structure
ARModel <- update(timeRS, correlation = corAR1(0, form = ~Time.Numeric|Person))
summary(ARModel)
anova(intercept, randomIntercept, timeRI, timeRS, ARModel)
anova读出的模型比较现在完全如书中所示。