2012-03-08 20 views
0

我有一個文件,我想重塑它以使用R:這些是我正在運行的命令。聚合需要fun.aggregate:默認使用的長度

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。我不知道發生了什麼事情?

+0

在第一行有一個右側缺失。 (和)哪個版本的重塑? – 2012-03-08 16:50:41

+0

'cast'已被'rescast2'中的'dcast'和'acast'取代 – Maiasaura 2012-03-08 17:02:49

+0

我試圖使用reshape2和dcast和acast,而不是工作值正在成爲NA。有任何想法嗎? – 2012-03-08 18:04:59

回答

4

澄清:在下面的討論中,我指的是dcast()而不是cast()。正如Maiasaura在評論中指出的,來自reshape包的函數cast()已被reshape2包中的兩個函數dcast()(用於數據幀輸出)和acast()(用於陣列或矩陣輸出)替代。在任何情況下,我對fun.aggregate參數的必要性的評論同樣適用於cast(),dcast()acast()


錯誤被拋出,因爲在調用分類變量的至少一個組合cast(),您data.frame y必須包含數據的至少兩行。作爲記錄在?cast(或?dcast):

If the combination of variables you supply does not uniquely identify one row in the original data set, you will need to supply an aggregating function, ‘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) 
+0

找不到dcast,我控制了它,但仍然掛起: – 2012-03-08 17:55:40

+0

我應該澄清一下:'reshape'包中的'cast()'已被棄用,並且被'dcast()'取代(當需要數據時。幀輸出)和'acast()'(當你想要數組或矩陣輸出時)。要找到'dcast',你需要先做:'install.packages(「reshape2」);庫(reshape2)'。但是,更大的問題是,您是否嘗試在'fun.aggregate'參數中爲'cast()'提供函數的名稱。它應該與'cast()'一起工作,就像它已經替換它的'dcast'和'acast'函數一樣...... – 2012-03-08 18:07:07

+0

我已經安裝了reshape2並嘗試過了。當我使用這個yy < - dcast(y,主機名+日期+變量~MetricType,意思是) 所有的值都變成NA – 2012-03-08 18:12:40