title: R variable not found, but specifically defined
body: <p>I have written a function to run phylogenetic generalized least squares, and everything looks like it should work fine, but for some reason, a specific variable which is defined in the script (W) keeps coming up as undefined. I have stared at this code for hours and cannot figure out where the problem is.</p>
  
  <p>Any ideas?</p>
  
  <pre><code>myou &lt;- function(alpha, datax, datay, tree){
      data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)-&gt;dat
      colnames(dat)&lt;-c("Trait1","Trait2")
      W&lt;-diag(vcv.phylo(tree)) # Weights
      fm &lt;- gls(Trait1 ~ Trait2, data=dat, correlation = corMartins(alpha, tree, fixed = TRUE),weights = ~ W,method = "REML")
      return(as.numeric(fm$logLik))
  }
  
  corMartins2&lt;-function(datax, datay, tree){
      data.frame(datax[tree$tip.label,],datay[tree$tip.label,],row.names=tree$tip.label)-&gt;dat
      colnames(dat)&lt;-c("Trait1","Trait2")
      result &lt;- optimize(f = myou, interval = c(0, 4), datax=datax,datay=datay, tree = tree, maximum = TRUE)
      W&lt;-diag(vcv.phylo(tree)) # Weights
      fm &lt;- 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&lt;-rcoal(50)
  as.data.frame(fastBM(simtree))-&gt;dat1
  as.data.frame(fastBM(simtree))-&gt;dat2
  
  corMartins2(dat1,dat2,tree=simtree)
  </code></pre>
  
  <p>returns "Error in eval(expr, envir, enclos) : object 'W' not found"</p>
  
  <p>even though W is specifically defined!</p>
  
  <p>Thanks!</p>