GlobalLocal Variable Scoping Difficulty in R

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I ve been trying to dust off my R skills recently and I ve been having some difficulty with variable scoping in this particular code.

So my function loop here calls other functions within the program that currently work without any problem calling years and trials (both ints), and simMat (a matrix of numeric). Where my main question lies is with the matrix simMat. I want to be able to call it from the command line and see the values but whenever I do that I ll get a matrix of NAs and I don t know why. I am nearly positive that is something to do with the variable scoping but I am not very familiar with that. Also, the suppressWarnings are to get rid of messages about coercion (don t know a lot about that either, any recommendation is appreciated)

I want to be able to call simMat form the command line and pass it to another function to do some arithmetic. I would greatly appreciate any help here on how I can accomplish this!!!

#This looks the same for the func asking for the num of years and trials
numTrials <- function()
{ 
  trials<- readline(prompt="How many trials? ")
  trials<- as.integer(trials)
  if (is.na(trials)){
    trials<- readinteger()
  }
  return(trials)
}

#Do the simple cash flow simulation
loop<-function(trials, years)
{
  trials<-suppressWarnings(numTrials())
  years<-suppressWarnings(numYears())
  simMat<-matrix(nrow=trials, ncol=years)
  for (i in 1:trials){
    sim <- newCashFlow[1]
    for (j in 1:years){
      simMat[i,j]<-sim
      random<-randomRates(cholMat2)
      sim = sim + sum(random*newCashFlow[j]*weights)
    }
  }
  simMat
  plotSimulation(simMat,years,i)
}

Answers

If you intend to access something from the console of R which is acting within the global environment, then you need to create the variable OUTSIDE of the function, in that environment you will be working in. As such it will persist when the loop function has completed its tasks.

To be able to use the matrix simMat outside of the loop create it there.

Also, before doing so, run the following script in your code to see where each variable lives. This will help you understand what happens as you make changes.

Sys.getenv(c("simMat", "trials", "years", "sim"))

or simply call the environment with parent.env(simMat)

This website is a very good one to explain these environment issues.

http://adv-r.had.co.nz/Environments.html http://adv-r.had.co.nz/Environments.html

http://adv-r.had.co.nz/Functions.html#lexical-scoping http://adv-r.had.co.nz/Functions.html#lexical-scoping

These two sites should get you past anything!

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/37166379/global-local-variable-scoping-difficulty-in-r

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils