我有一个文件要重塑以使用R:这些是我正在运行的命令。
x <- data.frame(read.table("total.txt", sep=",", header=T)
y <- melt(x, id=c("Hostname", "Date", "MetricType"))
Run Code Online (Sandbox Code Playgroud)
当我发出此命令将日期和小时基本结合在一起时,出现错误,窗口挂起。
yy <- cast(y, Hostname + Date + variable ~ MetricType)
Run Code Online (Sandbox Code Playgroud)
这是错误:
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
Run Code Online (Sandbox Code Playgroud)
有没有挂服务器的简便方法?
当我使用library(reshape2)时,这:
yy <- acast(y, Hostname + Date + variable ~ MetricType, fun.aggregate=mean)
Run Code Online (Sandbox Code Playgroud)
所有值都变成NA。我不知道这是怎么回事?
澄清:在下面的讨论中,我指的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)
Run Code Online (Sandbox Code Playgroud)