Question

After cbind or rbind-ing a table object (for example, adding a margin of sums or somesuch), names of dimnames get lost (see y). I found this "workaround" but was wondering if there's an out of the bag solution to this that looks less hacky. Perhaps something that can be done on the fly? I would like to keep the object of class table.

>   (x <- table(1:3, sample(1:3), dnn = c("rows", "cols")))
    cols
rows 1 2 3
   1 1 0 0
   2 0 0 1
   3 0 1 0
>   (y <- cbind(x, "4" = 4:6)) # "rows" and "cols" get lost
  1 2 3 4
1 1 0 0 4
2 0 0 1 5
3 0 1 0 6
> names(dimnames(y)) <- names(dimnames(x))
> y
    cols
rows 1 2 3 4
   1 1 0 0 4
   2 0 0 1 5
   3 0 1 0 6
Was it helpful?

Solution

How about addmargins? It computes sums by default, but you can plug in any custom function(s). For example:

> addmargins(x, margin=c(2,2), FUN=list('sum', 'mean'))
Margins computed over dimensions
in the following order:
1: cols
2: cols
    cols
rows   1   2   3 sum mean
   1 0.0 1.0 0.0 1.0  0.5
   2 0.0 0.0 1.0 1.0  0.5
   3 1.0 0.0 0.0 1.0  0.5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top