0

I am trying to change the value of an object in R environment. The code is given thus. and the error message:

myco <- function(form, data, start,tol=1e-06,maxit=10000)
{
  env <- new.env(hash = TRUE, parent = environment(form))
  for(i in names(data)) assign(i, data[[i]], envir = env,inherit=T)
  ind <- as.list(start)
  assign("new",ind,envir=env,inherit=T)
  
  
  for(itr in 1:maxit){
    assign("old",new,envir=env,inherit=T)
    grad=deriv(expr=form[[3L]],names(ind))
    attr(eval(grad,envir=env),"gradient")->J
    yh=eval(form[[2L]],env)-eval(form[[3L]],env)
    new=old+MASS::ginv(t(J)%*%J)%*%t(J)%*%yh
    if(sum(abs(new-old))<tol) break
    
  }
  return(new)
}

myco(GDP~A*(Labor^c)*(Capital^b),data=dat,start=list(A=0.05,b=0.5,c=0.5))

and the error message is

Error in assign("new", ind, envir = env, inherit = T) : cannot change value of locked binding for 'new'

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Teniola
  • 3
  • 2
  • Please define all variables like `dat` so that we can copy/paste the code to run it and debug it. What exactly are you trying to accomplish with this code? Why are you creating all these environments? – MrFlick May 25 '22 at 17:04
  • form is formular – Teniola May 25 '22 at 17:12
  • 2
    we cannot debug anything if we dont know what data is passed to function; you need to provide at least stubs which are identical to your data – ivan866 May 25 '22 at 17:12
  • data is a dataframe object, start is a list object that contains the initial parameters, tol is a scalar (the tolerance value) and maxit is the maximum iteration, a scalar also – Teniola May 25 '22 at 17:13
  • 1
    This function does not make sense (to me). Why are you assigning `data[[i]]` to `i` with `assign(i, data[[i]], envir = env,inherit=T)`? A for-loop iterates over data, with every loop changing the value of `i` through the vector `names(data)`. You should not assign `i` within the loop. Also, `<-` should be used for assignment. – bash1000 May 25 '22 at 17:15
  • 2
    @Teniola why are you doing `as.list()` on an already `list` parameter? (line 5) – ivan866 May 25 '22 at 17:20
  • 1
    @Teniola your whole iteration loop makes no sense, as it doesnt iterate over any parameter; it simply does 10000 times the same operation, overwriting your `new` variable each time; also, assigning variable INSIDE the loop is a bad habit, especially if you are going to `return` it - which you do – ivan866 May 25 '22 at 17:22

0 Answers0