我想用 nls 做一个有 2 个分类变量的模型 makeham,只有 1 个变量可以工作。
例如,
# Create the data
df <- data.frame(edad = c(30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35),
maduraciongrp = c("0-1", "0-1", "2", "2", "3+", "3+", "0-1", "0-1", "2", "2", "3+", "3+", "0-1", "0-1", "2", "2", "3+", "3+","0-1", "0-1", "2", "2", "3+", "3+", "0-1", "0-1", "2", "2", "3+", "3+", "0-1", "0-1", "2", "2", "3+", "3+"),
origen = c("0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "1"),
expuestos = sample(100:500, 36),
dec = sample(1:90, 36)
)
df <- df %>% mutate(mx=dec/expuestos, maduraciongrp=maduraciongrp %>% as.factor())
# craete model gompertz to obtain b0 and b1
gompertz<-nls(mx ~exp(b0 + b1 * edad), start =list(b0 =1,b1 =0),weights = expuestos, data= df)
# Create model makeham with 1 categorical variable
makeham1<-nls(mx ~ a[maduraciongrp] + exp(b0 + b1 * edad), data= df,
start =list(b0 =coef(gompertz)[1],b1 =coef(gompertz)[2], a=rep(0, nlevels(df$maduraciongrp))),
weights =expuestos)
现在我想包含其他分类变量,我正在使用以下代码
makeham1<-nls(mx ~ a[maduraciongrp] + b[origen] + exp(b0 + b1 * edad), data= df,
start =list(b0 =coef(gompertz)[1],b1 =coef(gompertz)[2], a=rep(0, nlevels(df$maduraciongrp)),
b=rep(0, 2)), weights =expuestos)
但出现以下错误
Error in numericDeriv(form[[3L]], names(ind), env) :
Missing value or an infinity produced when evaluating the model
如何将第二个分类变量包含到我的模型中?