在cbind或rbind之后丢失表的dimnames的名称

时间:2012-02-09 15:13:41

标签: r names rbind

cbindrbind表格对象之后(例如,添加一个总和或某些边距),dimnames的名称会丢失(请参阅y)。我找到了这个“解决方法”但是想知道是否有一个解决方案,看起来不那么黑客。也许可以在飞行中完成的事情?我想保留班级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 个答案:

答案 0 :(得分:3)

addmargins怎么样?它默认计算总和,但您可以插入任何自定义函数。例如:

> 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