2

我已经编写了一个函数来运行系统发育广义最小二乘法,一切看起来都应该可以正常工作,但由于某种原因,脚本中定义的特定变量 (W) 不断出现未定义。我盯着这段代码看了好几个小时,无法弄清楚问题出在哪里。

有任何想法吗?

myou <- function(alpha, datax, datay, tree){
    data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)->dat
    colnames(dat)<-c("Trait1","Trait2")
    W<-diag(vcv.phylo(tree)) # Weights
    fm <- gls(Trait1 ~ Trait2, data=dat, correlation = corMartins(alpha, tree, fixed = TRUE),weights = ~ W,method = "REML")
    return(as.numeric(fm$logLik))
}

corMartins2<-function(datax, datay, tree){
    data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)->dat
    colnames(dat)<-c("Trait1","Trait2")
    result <- optimize(f = myou, interval = c(0, 4), datax=datax,datay=datay, tree = tree, maximum = TRUE)
    W<-diag(vcv.phylo(tree)) # Weights
    fm <- gls(Trait1 ~ Trait2, data = dat, correlation = corMartins(result$maximum, tree, fixed =T),weights = ~ W,method = "REML")
    list(fm, result$maximum)}




#test


require(nlme)
require(phytools)
simtree<-rcoal(50)
as.data.frame(fastBM(simtree))->dat1
as.data.frame(fastBM(simtree))->dat2

corMartins2(dat1,dat2,tree=simtree)

返回“评估错误(expr,envir,enclos):找不到对象'W'”

即使 W 是明确定义的!

谢谢!

4

2 回答 2

6

错误发生在gls调用myou和中corMatrins2:您必须W作为一列传入,dat因为gls正在那里寻找它(当您weights = ~W输入像它寻找dat$W但找不到的公式时)。

只需在这两个功能中更改data=datdata=cbind(dat,W=W)

于 2012-05-16T23:50:19.383 回答
5

该示例对我来说是不可重现的,因为lowerB并且upperB没有定义,但是,也许以下内容对您cbinding dat有用W

myou <- function(alpha, datax, datay, tree){
    data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)->dat
    colnames(dat)<-c("Trait1","Trait2")
    W<-diag(vcv.phylo(tree)) # Weights
            ### cbind W to dat
            dat <- cbind(dat, W = W)
    fm <- gls(Trait1 ~ Trait2, data=dat, correlation = corMartins(alpha, tree, fixed = TRUE),weights = ~ W,method = "REML")
    return(as.numeric(fm$logLik))
}

corMartins2<-function(datax, datay, tree){
    data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)->dat
    colnames(dat)<-c("Trait1","Trait2")
    result <- optimize(f = myou, interval = c(lowerB, upperB), datax=datax,datay=datay, tree = tree, maximum = TRUE)
    W<-diag(vcv.phylo(tree)) # Weights
    ### cbind W to dat
    dat <- cbind(dat, W = W)
    fm <- gls(Trait1 ~ Trait2, data = dat, correlation = corMartins(result$maximum, tree, fixed =T),weights = ~ W,method = "REML")
    list(fm, result$maximum)}




#test
require(phytools)
simtree<-rcoal(50)
as.data.frame(fastBM(simtree))->dat1
as.data.frame(fastBM(simtree))->dat2

corMartins2(dat1,dat2,tree=simtree)
于 2012-05-16T23:52:32.353 回答