這是很多複雜得多,我想,但我認爲這是必要:
##' 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)
非常感謝!這解決了我的問題。 – devdreamer