From murdoch.duncan at gmail.com  Mon Jun 17 19:40:49 2013
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Mon, 17 Jun 2013 13:40:49 -0400
Subject: [Rd] Odd behavior of symbol objects with classes/attributes
In-Reply-To: <CAFOpNVER4Vxf6rmXWTOHiywcyFsFUjuaAdFNGoae_gMh3KMvnA@mail.gmail.com>
References: <CAFOpNVER4Vxf6rmXWTOHiywcyFsFUjuaAdFNGoae_gMh3KMvnA@mail.gmail.com>
Message-ID: <51BF4A21.307@gmail.com>

On 17/06/2013 1:01 PM, Winston Chang wrote:
> I've been trying to add classes and attributes to symbol objects
> (created with quote()), and the behavior is very strange, as
> illustrated in the examples below.
>
> If symbols aren't meant to have classes and attributes attached to
> them, then perhaps R should throw errors when you attempt to do it?

I think this is a consequence of another strange property of symbol 
objects, namely that they are not copied on assignment.  This is also 
true of environments, NULL, builtin function references, and some rarely 
encountered types like external pointers and weak references.  You're 
allowed to assign attributes to all of these other than NULL, but you 
will find strange things happen if you do it (as demonstrated in your 
code below).

I thought I remembered reading a list of these in the documentation 
somewhere, but when I went to look for it just now, I couldn't find it.  
(Maybe I'm remembering a comment in the source.)  It would be a useful 
addition.

Duncan Murdoch

>
>
> # Using str() strips class from object
> x <- quote(foo)
> class(x) <- "bar"
> str(x)
> # Class 'bar'  symbol foo
> str(x)
> # symbol foo
>
>
> # Attempting to overwrite doesn't affect class.
> # str() still strips class from the object.
> x <- quote(foo)
> class(x) <- "bar"
> x <- quote(foo)
> str(x)
> # Class 'bar'  symbol foo
> str(x)
> # symbol foo
>
>
> # Changing class of one object affects other
> x <- quote(foo)
> y <- quote(foo)
> class(x) <- "bar"
> class(y)
> # [1] "bar"
> str(y)
> # Class 'bar'  symbol foo
> str(y)
> # symbol foo
> str(x)
> # symbol foo
>
>
> # Changing attribute of one object affects other
> # Unlike with class, str() doesn't cause other attributes to disappear
> x <- quote(foo)
> y <- quote(foo)
> attr(x, "a") <- "bar"
> str(y)
> # length 1 foo
> # - attr(*, "a")= chr "bar"
> str(y)
> # length 1 foo
> # - attr(*, "a")= chr "bar"
> str(quote(foo))
> # length 1 foo
> # - attr(*, "a")= chr "bar"
>
>
> -Winston
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Odd behavior of symbol objects with classes/attributes
Duncan Murdoch