On 11-01-22 3:06 AM, Lui ## wrote:
Hello everybody,

I have a problem that is bothering me for  quite a while now and I
don't know the answer... I want to create global variables (out of a
function) which I can access from all other functions... But somehow
that does not work too well. Attached some code for an example:

function_called<- function (){
        result = globalvariable*globalvariable
        print(result)
        
        }

function_calls<- function(){
        assign("globalvariable",10,pos=-1,envir=as.environment(pos))

This line doesn't make sense. Why specify both pos and envir? I would have used envir=globalenv() to do what you want; the help page indicates that pos=globalenv() is preferred by whoever wrote it. But don't use both.

However, an even simpler approach is simply

globalvariable <<- 10

This will search back through the environments associated with the function_calls function (not the call stack!) for a variable named globalvariable, and make the assignment to it. If none exists, it will use the global environment.

Duncan Murdoch

        function_called()
        }

function_calls()

I would have assumed that I will get "100" printed on my screen, but
instead it said: "Fehler in function_called() : Objekt
'globalvariable' nicht gefunden", so the function "function_called"
did not have access to the variable "globalvariable".

I would be very thankful for some help... I want to implement it in
the genetic algorithms provided by the rgenoud package and dont know
any other way to have "changing" constraints (e.g. Portfolio
optimization and covariance matrix).
Thanks in advance! Any help greatly appreciated!

Lui

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to