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

Duncan Murdoch murdoch.duncan at gmail.com
Tue Apr 30 11:49:05 CEST 2013


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
>



More information about the R-devel mailing list