【问题标题】:Losing names of dimnames of a table after cbind or rbind在 cbind 或 rbind 之后丢失表的名称的名称
【发布时间】:2012-03-02 01:51:35
【问题描述】:

cbindrbind-ing 一个表格对象之后(例如,添加总和的边距等),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

【问题讨论】:

  • 这甚至不能满足您的需求,因为“y”不再是 class==“table”。
  • 现在呢? :) as.table(as.table(y))

标签: r names rbind


【解决方案1】:

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

【讨论】:

  • 我一直在使用margin.table,但没有注意到addmargins(链接到margin.table)真的很有用。谢谢你。稍作修改(addmargins(x, margin=c(1,2), FUN=list(total = 'sum'), quiet = TRUE)),我就非常优雅地得到了我想要的东西。
  • 但是平均值是在 3 个表列和总和列上计算的,所以实际上它是错误的。有没有办法解决这个问题?
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多