R变量未找到,但具体定义

时间:2012-05-16 23:32:10

标签: r function

我编写了一个函数来运行系统发育的广义最小二乘法,一切看起来应该可以正常工作,但由于某种原因,脚本(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)

返回&#34; eval中的错误(expr,envir,enclos):object&#39; W&#39;找不到&#34;

即使W是专门定义的!

谢谢!

2 个答案:

答案 0 :(得分:6)

glsmyou中的corMatrins2来电中出现错误:您必须将W作为dat中的列传递,因为{{1}在那里寻找它(当你将gls作为一个公式时,它会查找weights = ~W并找不到它。)

只需在两个功能中将dat$W更改为data=dat

答案 1 :(得分:5)

该示例对我来说无法重现,因为lowerBupperB未定义,但是,以下内容可能对您有用cbinding dat W 1}}:

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)