[Rd] The default behaviour of a missing entry in an environment

Duncan Murdoch murdoch at stats.uwo.ca
Fri Nov 13 20:27:57 CET 2009


On 11/13/2009 2:03 PM, Trishank Karthik Kuppusamy wrote:
> Greetings everyone,
> 
> I have a question about the default behaviour of a missing entry in an environment.
> Let us look at the following sequence of R statements:
> 
>> e <- new.env()
>> e$a <- 1
>> e$a
> [1] 1
>> e$b
> NULL
>> 
> 
> I think I understand the logic for returning NULL to a missing entry in an environment,
> but I do not think that it is fully justified.
> I am sure that the R developers must have seen this argument before,
> but I wish to call for attention to this problem again,
> because I think that it is important to the default safety of the R programming language.

You get the same behaviour when asking for a nonexistent element of a 
list, or a nonexistent attribute.   If you want stricter checking, don't 
use $, use get():

 > get("b", e)
Error in get("b", e) : object 'b' not found

or check first with exists():

 > exists("b", e)
[1] FALSE

> I suppose that one could argue that a good R programmer must be careful
> not to use NULL in any of his environment entries,
> but I think it is better to remove altogether this burden from the programmer
> and simply raise a good, old-fashioned exception when the "$" operator
> encounters a missing entry in an environment.

But then it would be inconsistent with what it does in other situations.

Duncan Murdoch

> The biggest advantage is that it will easily eliminate a whole class of programming error.
> The biggest disadvantage is that it is not backwards-compatible with old R programs.
> 
> I suppose a personal solution would be to simply redefine the "$" operator in my programs.
> However, I really do think that the default safety of an R environment matters very much.
> At the very least, it would be nice to be able to configure the safety of a new environment,
> perhaps through a parameter.
> 
> -Trishank
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list