我正在尝试使用一种方法来自动确定和删除混合模型语句中的固定效果的方法lmer
。简而言之,我的方法是用于fixef
获取固定效果名称,然后用于update
从模型语句中删除这些名称。我遇到了一些障碍...
首先,如果固定因子不连续,则fixef
返回变量名称以及处理级别(例如,levels(variable1)=c("A","B","C")
将返回variable1B
和variable1C
)。我试图通过部分匹配来解决这个问题,但是我相信它不会在所有情况下都成功(请参见下文)。
其次,如果存在交互作用,则部分匹配会分解并仅识别第一项(例如,仅从variable1
返回variable1:variable
)。我不确定该如何解决。
这是一些示例代码:
#Create example data
set.seed(9)
data=data.frame(y=rnorm(100,5,10),y.binom=rbinom(100,1,0.5),
y.poisson=rpois(100,5),fixed1=rnorm(100,20,100),
fixed2=c("Treatment1","Treatment2"),covar=rnorm(100,20,100),
rand1=LETTERS[1:2],
rand2=c(rep("W",25),rep("X",25),rep("Y",25),rep("Z",25)))
library(lme4)
#Fit generalized linear mixed effects model
mod=glmer(y.poisson~fixed1*fixed2+covar+(1|rand2/rand1),family="poisson",data)
#Pull out names of fixed effects
fixef.names=do.call(rbind,lapply(1:length(names(fixef(mod))[-1]),function(j) {
d=colnames(mod@frame)[pmatch(colnames(mod@frame),names(fixef(mod))[-1][j])>0]
d[!is.na(d)] } ) )[,1]
# Generate null model (intercept and random effects only, no fixed effects)
null.mod=update(mod,paste(".~.-",paste(fixef.names,collapse="-"),sep=""))
任何帮助表示赞赏!
其中有一个内置findbars()
功能,lme4
可助您一臂之力。您仍然需要删除结果(它们作为language
对象返回);用括号保护它们;并将其重新粘贴到公式中。但这似乎可行:
parens <- function(x) paste0("(",x,")")
onlyBars <- function(form) reformulate(sapply(findbars(form),
function(x) parens(deparse(x))),
response=".")
onlyBars(formula(mod))
## . ~ (1 | rand1:rand2) + (1 | rand2)
update(mod,onlyBars(formula(mod)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句