5

在对表格对象进行cbindrbind-ing 之后(例如,添加总和的边距等),dimnames 的名称会丢失(请参阅 参考资料y)。我找到了这个“解决方法”,但想知道是否有现成的解决方案来解决这个问题,看起来不那么老套。也许可以即时完成一些事情?我想保留 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
4

1 回答 1

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
于 2012-02-09T16:04:54.723 回答