[R] how to determine if a variable is already set?

Don MacQueen macq at llnl.gov
Sat Sep 12 23:33:49 CEST 2009


Do watch out, however, for *where* i exits.

That is, if you type search() you will see a list of environments in 
which i might be found. You're probably assuming that i, if 
exists("i") is true, is in .GlobalEnv, but it might be in one of the 
other environments, in which case exists('i') will be TRUE, but it 
won't be the i you are looking for.

I believe you need to quote then name also
    use:    exits('i')
    not:    exists(i)

See  ?exists (again)

-Don


At 10:19 AM -0700 9/12/09, carol white wrote:
>Thanks for your replies.
>
>I use the following script:
>
>if(!exists(i)) stop ("set the variable i", call. = FALSE)
>
>but before the stop expression, Error gets displayed:
>
>Error: set the variable i
>
>Is there another function that stops the execution, prints an 
>expression without printing Error or any other expression except the 
>expression parameter?
>
>Best,
>
>
>
>--- On Fri, 9/11/09, Marc Schwartz <marc_schwartz at me.com> wrote:
>
>From: Marc Schwartz <marc_schwartz at me.com>
>Subject: Re: [R] how to determine if a variable is already set?
>To: "carol white" <wht_crl at yahoo.com>
>Cc: r-help at stat.math.ethz.ch
>Date: Friday, September 11, 2009, 10:21 AM
>
>On Sep 11, 2009, at 12:15 PM, carol white wrote:
>
>>  Hi,
>>  It might be a primitive question but how it is possible to 
>>determine if a variable is initialized in an environment? Suppose 
>>that we start a R session and wants to run a script which use the 
>>variable i. Which function could evaluate if i is already 
>>initialized or not and if not, then ask interactively the user to 
>>set it? This is to avoid the error message: object i is not found.
>>
>>  Regards,
>>
>>  Carol
>
>
>See ?exists
>
>Note that this will tell you if the object exists, not if it 
>contains a specifically desired initial value. You would have to 
>check for the latter after determining that the object does indeed 
>exist.
>
>HTH,
>
>Marc Schwartz
>
>
>
>
>      
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at 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.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list