Losing names of dimnames of a table after cbind or rbind

ぐ巨炮叔叔 提交于 2019-12-06 02:36:45

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/9213468/losing-names-of-dimnames-of-a-table-after-cbind-or-rbind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!