2012-02-09 74 views
5

cbind或之后(例如,添加一个或多个和的余量),昏暗名称会丢失(请参阅y)。我发现这个“解决方法”,但想知道是否有一个解决方案,这看起来不那么hacky。也许有些事情可以在飞行中完成?我想保留类table的对象。在cbind或rbind之后丢失表名的名称

> (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 
+0

这甚至没有做你想做的,因为“y”不再是class ==“table”。 – 2012-02-09 16:23:33

+0

现在呢? :) as.table(as.table(y))' – 2012-02-09 23:57:54

回答

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 
+0

我一直在使用'margin.table',但没有注意到'addmargins'(从'margin.table'链接)真的有用。谢谢。稍微修改一下('addmargins(x,margin = c(1,2),FUN = list(total ='sum'),quiet = TRUE)'),我就可以非常优雅地得到我想要的东西。 – 2012-02-10 00:02:06

+0

然而,平均值是通过3个表格列和和列来计算的,所以实际上这是错误的。有没有解决的办法? – ivan 2017-07-18 18:38:40