【问题标题】:Automatic column name label with cast带有强制转换的自动列名标签
【发布时间】:2012-07-06 10:00:08
【问题描述】:

使用 reshape::cast 时,有没有办法设置结果列的名称?

例子:

library(reshape)
data(mtcars)
cast(mtcars, cyl + hp ~ .,mean)

   cyl  hp (all)
1    4  52     2
2    4  62     2
3    4  65     1
4    4  66     1
5    4  91     2

我希望能够在调用 cast 时设置名称,而不是 (all)。这可能吗?

我知道,我知道,好像输入colnames(x)[3] <- "Foo" 太难了,但如果你必须经常这样做,那就太费时间了!

【问题讨论】:

  • 能否让您的示例可重现(包括加载必要的包等)?
  • 你确定你从 reshape2 得到cast 吗?我以为那个函数被dcast替换了?
  • reshape2 被@chase(不是 OP)添加为编辑,我有一个修订版将其设置为reshapereshape2 将使用 dcast 并返回 NA 列名而不是 (all)
  • @mnel - 哦!对那里的混乱感到抱歉......我的帮助适得其反......我会回到我的洞穴。
  • 最好的解决方案是向@hadley 发送功能请求:-p

标签: r reshape


【解决方案1】:

创建一个新的包装器,提供您寻求的设施(这意味着我找不到可以做到这一点的现有参数):

bcast <- function(... , agg.name =NA){ res <- cast(...)
             if(!is.na(agg.name)){ names(res)[length(res)] <- agg.name } 
             res}
bcast(mtcars, cyl + hp ~ . ,  fun.aggregate= mean, agg.name="test")

#--------
#Using carb as value column.  Use the value argument to cast to override this choice
#   cyl  hp test
1    4  52    2
2    4  62    2
3    4  65    1
4    4  66    1
5    4  91    2
6    4  93    1
7    4  95    2
snipped output....

【讨论】:

    【解决方案2】:

    对于示例中的简单整形,您可以简单地在基础 R 中使用 aggregate,它可以满足您的需求,而无需指定列名:

    aggregate(carb~cyl+hp, mtcars, FUN=mean)
    
       cyl  hp carb
    1    4  52    2
    2    4  62    2
    3    4  65    1
    4    4  66    1
    5    4  91    2
    .....
    

    或在所有列上:

    aggregate(.~cyl+hp, mtcars, FUN=mean)
    
       cyl  hp      mpg     disp     drat       wt     qsec        vs        am     gear carb
    1    4  52 30.40000  75.7000 4.930000 1.615000 18.52000 1.0000000 1.0000000 4.000000    2
    2    4  62 24.40000 146.7000 3.690000 3.190000 20.00000 1.0000000 0.0000000 4.000000    2
    3    4  65 33.90000  71.1000 4.220000 1.835000 19.90000 1.0000000 1.0000000 4.000000    1
    4    4  66 29.85000  78.8500 4.080000 2.067500 19.18500 1.0000000 1.0000000 4.000000    1
    5    4  91 26.00000 120.3000 4.430000 2.140000 16.70000 0.0000000 1.0000000 5.000000    2
     .....
    

    【讨论】:

      【解决方案3】:

      reshape::cast 中无法设置默认列名,但在reshape2::dcast 中可以设置(无论如何你都可以使用它,因为它更快)。使用您的示例:

      dcast (mtcars, cyl + hp ~ "colname", mean)
      

      【讨论】:

      • 好的,但正如我刚刚从今天的 Hadley 的 post 中了解到的那样,这种行为是一个错误 - 不幸的是。
      猜你喜欢
      • 1970-01-01
      • 2022-11-05
      • 2011-10-10
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2017-06-17
      相关资源
      最近更新 更多