聚合需要fun.aggregate:默认使用的长度

时间:2012-03-08 16:45:36

标签: r reshape

我有一个文件,我想重塑它以使用R:这些是我正在运行的命令。

x <- data.frame(read.table("total.txt", sep=",", header=T)
y <- melt(x, id=c("Hostname", "Date", "MetricType"))

当我发出此命令基本上将日期与小时结合时,我收到错误并且窗口挂起。

yy <- cast(y, Hostname + Date + variable ~ MetricType)

这是错误:

Aggregation requires fun.aggregate: length used as default
       ServerNa Date       MetricType   Hour   Value
19502  server1 01/05/2012  MemoryAVG    Hour5  41.830000
19503  server1 01/05/2012 CPUMaximum    Hour5   9.000000
19504  server1 01/05/2012 CPUAVG+Sev    Hour5   9.060000
19505  server1 01/05/2012     CPUAVG    Hour5  30.460000
19506  server1 01/05/2012         61    Hour5  63.400000
19507  server1 01/05/2012         60    Hour5  59.300000
19508  server2 01/05/2012  MemoryAVG    Hour5  10.690000
19509  server2 01/05/2012 CPUMaximum    Hour5   1.000000
19510  server2 01/05/2012 CPUAVG+Sev    Hour5   0.080000
19511  server2 01/05/2012     CPUAVG    Hour5   1.350000

有没有一种简单的方法可以在不挂起服务器的情况下执行此操作?

当我使用库(reshape2)时:

yy <- acast(y, Hostname + Date + variable ~ MetricType, fun.aggregate=mean)

所有值都变为NA。我不知道发生了什么事?

1 个答案:

答案 0 :(得分:4)

澄清:在下面的讨论中,我引用dcast()而不是cast()。正如Maiasaura在评论中指出的那样,cast()包中的函数reshape已被reshape2包替换为两个函数:dcast()(对于data.frame输出)和acast()(用于数组或矩阵输出)。无论如何,我对fun.aggregate论证需求的评论同样适用于cast()dcast()acast()


引发错误是因为对于cast()调用中的至少一个分类变量组合,您的data.frame y必须包含至少两行数据。如?cast(或?dcast)中所述:

  

如果您提供的变量组合不是唯一的     识别原始数据集中的一行,您需要提供     聚合函数'fun.aggregate'。

运行以下代码,了解其工作原理以及如何解决问题。在最后一行代码中,我使用fun.aggregate参数告诉dcast()使用mean()组合任何重复变量组合的值。取而代之的是,您可以放置​​最适合您自己情况的聚合函数。

library(reshape2)

## A toy dataset, with one row for each combination of variables
d <- expand.grid(Hostname = letters[1:2],
                 Date = Sys.Date() + 0:1,
                 MetricType = LETTERS[3:4])
d$Value <- rnorm(seq_len(nrow(d)))

## A second dataset, in which one combination of variables is repeated
d2 <- rbind(d, d[1,])

## Runs without complaint
dcast(d, Hostname + Date ~ MetricType)

## Throws error asking for an aggregation function
dcast(d2, Hostname + Date ~ MetricType)

## Happy again, with a supplied aggregation function
dcast(d2, Hostname + Date ~ MetricType, fun.aggregate=mean)
相关问题