[R] Calling object outside function

Adaikalavan Ramasamy a.ramasamy at imperial.ac.uk
Wed Sep 24 21:18:42 CEST 2008


I don't understand why you need to use a function at all, especially 
when all your function arguments are overwritten inside the loop.

Here is a simplified example of what you are doing:

f <- function(x){
  x <- 5
  print(x)
}

Therefore f(1), f(2), ..., f(1000) etc all gives you the same answer.

However, you can set a default value for x, which will allow you to vary 
it at a later stage if you wish to.

f <- function(x=5){
  print(x)
}

So now f() gives 5, f(10) gives 10, ...


Similarly, assuming that you want to vary the file, Loc_Mod_TAZ, 
Dev_Size later, you might be interested in perhaps:

loadTestData <- function(file="TAZ_VAC_ACRES.csv",
                          Loc_Mod_TAZ=120, Dev_Size=58){

    #Loads TAZ and corresponding vacant acres data
    TAZ_VAC_ACRES <- read.csv(file=file,header=TRUE);

    #Determines vacant acres by TAZ
    TAZDetermine=TAZ_VAC_ACRES[TAZ_VAC_ACRES$TAZ==Loc_Mod_TAZ,2]
    return(TAZDetermine)
}

out <- LoadTestData()

Regards, Adai



PDXRugger wrote:
> What i thought was a simple process isnt working for me.  After i create an
> multiple objects in a function (see below), how to i use those objects later
> in the program.  I tried calling the function again and then the object i
> wanted and it worked the first time but now it doesnt( i think i defined the
> object outside the function accidently so then it worked but when run
> properly it doesnt).  I did this using 
> Testdata(TAZDetermine) to first recall the function then the object i wanted
> to use.  This deosnt work and it errors that the object cannot be found.  Do
> i use attach?  this didnt seem to work either.  I just want to call an
> object defined in a function outside of the function.  Hope you can help
> 
> Cheers,
> JR
> 
> 
> #Function to create hypothetical numbers for process testing 
> Testdata=function(TAZ_VAC_ACRES,Loc_Mod_TAZ,Dev_Size,TAZDetermine,Dev_Size){
> 
> #Loads TAZ and corresponding vacant acres data
> TAZ_VAC_ACRES=
> read.csv(file="I:/Research/Samba/urb_transport_modeling/LUSDR/Workspace/BizLandPrice/data/TAZ_VAC_ACRES.csv",header=TRUE);
> 
> 
> #Test Location Choice Model selected TAZ 
> Loc_Mod_TAZ = 120
> #Create test Development 
> Dev_Size=58
> 
> #Determines vacant acres by TAZ 
> TAZDetermine=TAZ_VAC_ACRES[TAZ_VAC_ACRES$TAZ==Loc_Mod_TAZ,2]
> 
> #Displays number of vacant acres in Location Choice Model selected TAZ
> TAZDetermine
> 
> }
> 
> Testdata(TAZDetermine)
> 
> error indicating the that function cannot be found even thoug its part of
> the argument list in the main function.  
>



More information about the R-help mailing list