2015-08-26 64 views
2

我想建立一個混合效應模型驗證工具,我使用的是正向選擇方法,所以如果假設模型是model<-y~a+b+(1+c|d)(包括隨機截距和隨機斜率),我可以在R findbars(model)的lme4包中使用findbars函數來分離隨機效應,即本例中的(1+c|d),但由於我使用的是正向選擇方法,我首先需要隨機截取模型,即(1|d),然後是完整的隨機效應模型(1+c|d)。如果我在模型中看到(1+c|d),是否有任何方法來分割隨機效果(1|d)公式操作(分裂隨機效應)

回答

2

這是很多複雜得多,我想,但我認爲這是必要:

##' combine unary or binary operator + arguments (sugar for 'substitute') 
makeOp <- function(x,y,op=NULL) { 
    if (is.null(op)) { ## unary 
    substitute(OP(X),list(X=x,OP=y)) 
    } else substitute(OP(X,Y), list(X=x,OP=op,Y=y)) 
} 
## convert character to raw 'language' object 
toLang <- function(x) parse(text=x)[[1]] 
## expand term using terms() 
splitFun <- function(x) { 
    tt <- terms(as.formula(makeOp(x,quote(`~`)))) 
    res <- lapply(attr(tt,"term.labels"),toLang) 
    if (attr(tt,"intercept")==1) { 
     res <- c(list(1),res) 
    } 
    return(res) 
} 
## expand left-hand side terms into a list, 
## distribute across right-hand sides 
expandFun <- function(x) { 
    lapply(splitFun(x[[2]]),makeOp,y=x[[3]],op=quote(`|`)) 
} 

試試看:

form <- y~a+b+(1+c|d) 
bb <- lme4::findbars(form) 
lapply(bb,expandFun) 
## [[1]] 
## [[1]][[1]] 
## 1 | d 
## 
## [[1]][[2]] 
## c | d 

此代碼也將擴大,例如x*y分成1+x+y+x:y(不知道你是否想要這樣做......

PS:你知道逐步選擇模型的推理性危險,對嗎? (例如見here

+0

非常感謝!這解決了我的問題。 – devdreamer