From murdoch.duncan at gmail.com  Tue Apr 30 11:49:05 2013
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Tue, 30 Apr 2013 05:49:05 -0400
Subject: [Rd] Subset of a 'table' divided by a 'table' is a 'table',
 but printed by 'print.default'
In-Reply-To: <1367307525.65406.YahooMailClassic@web125103.mail.ne1.yahoo.com>
References: <1367307525.65406.YahooMailClassic@web125103.mail.ne1.yahoo.com>
Message-ID: <517F9391.3020406@gmail.com>

On 13-04-30 3:38 AM, Suharto Anggono Suharto Anggono wrote:
> This is just info.
>
> I recently got something like this.
>
>> x <- factor(c("A","A","B","B"), levels=c("A","B"))
>> y <- factor(c("a","b","a","b"), levels=c("a","b"))
>> table(x, y)[, "a"] / table(x)
> x
>    A   B
> 0.5 0.5
> attr(,"class")
> [1] "table"
>
> The printing indicates that the result is of class 'table'. But, the 'print' method of class 'table' does not print attr(,"class"). It seems that 'print.default' is used in the printing. I am OK with it, just unusual.
>
> I think, that is another symptom of an already known behavior as in the following:
> - PR#2345: difftime arithmetic
> - PR#13209: S4 object does not commute?

There are no S4 objects or time objects involved here, so it's likely 
something different.

I notice the following strange behaviour.  If I save the ratio in a 
variable, it prints differently with an explicit print than with auto 
printing:

x <- factor(c("A","A","B","B"), levels=c("A","B"))
y <- factor(c("a","b","a","b"), levels=c("a","b"))
ratio <- table(x, y)[, "a"] / table(x)
ratio          # shows what you saw
print(ratio)   # shows what you expected


Something else that's a little strange:  the numerator does not have 
class "table", so you can get the same results with

ratio <- c(1,1) / table(x)

Looking at the internals, I see that the ratio variable has a class 
attribute, but does not have its "object bit" set.

So it looks like the bug is in the implementation of "/".  Either it 
should drop the class, or it should set the object bit.

The difference in printing between auto-printing and explicit printing 
may be worth addressing, but really objects like ratio shouldn't exist, 
so it's not surprising that they behave strangely.

Duncan Murdoch


>
>
>> sessionInfo()
> R version 3.0.0 (2013-04-03)
> Platform: i386-w64-mingw32/i386 (32-bit)
>
> locale:
> [1] LC_COLLATE=English_United States.1252
> [2] LC_CTYPE=English_United States.1252
> [3] LC_MONETARY=English_United States.1252
> [4] LC_NUMERIC=C
> [5] LC_TIME=English_United States.1252
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] Subset of a 'table' divided by a 'table' is a 'table', but printed by 'print.default'
Duncan Murdoch