2013-12-19 65 views
2

一個data.frame我有一個溫度數據框:我把溫度在攝氏埃維一天每隔一小時,所以我有一個CSV文件是這樣的:重塑中的R

Day  Hour Temperature 
11/10/2013 9:00 6 
11/10/2013 10:00 11 
11/10/2013 11:00 13 
11/10/2013 12:00 6 
11/10/2013 13:00 8 
12/10/2013 9:00 7 
12/10/2013 10:00 8 
12/10/2013 11:00 11 
12/10/2013 12:00 18 
12/10/2013 13:00 12 
13/10/2013 9:00 15 
13/10/2013 10:00 8 
13/10/2013 11:00 11 
13/10/2013 12:00 16 
13/10/2013 13:00 9 

我試圖重新排序它的R中爲了得到改變標題文字,每天記錄:

Day  9:00 10:00 11:00 12:00 13:00 
11/10/2013 6  11 13 6  8 
12/10/2013 7  8 11 18 12 
13/10/2013 15  8 11 16  9 

我試過cbind的幾種組合,sapply和獨特的,但我不知道他們是否是右R元素重新排列我的數據。幀。任何想法,建議? 非常感謝

+3

看功能'dcast'在包reshape2。 – Roland

+0

@ user2261983當您提出問題時,請參閱我的回答,以獲取向其他人提供數據的有用方法。使用'dput(my_data)'是另一種選擇。 –

回答

2

這是您的數據作爲數據框架。

temperatures <- read.table(
    text = " Day  Hour Temperature 
    11/10/2013 9:00 6 
    11/10/2013 10:00 11 
    11/10/2013 11:00 13 
    11/10/2013 12:00 6 
    11/10/2013 13:00 8 
    12/10/2013 9:00 7 
    12/10/2013 10:00 8 
    12/10/2013 11:00 11 
    12/10/2013 12:00 18 
    12/10/2013 13:00 12 
    13/10/2013 9:00 15 
    13/10/2013 10:00 8 
    13/10/2013 11:00 11 
    13/10/2013 12:00 16 
    13/10/2013 13:00 9", 
    header = TRUE 
) 

下面是Roland建議的解決方案,採用dcast

library(reshape2) 
dcast(temperatures, Day ~ Hour, value.var = "Temperature") 

僅供參考,您的「重塑」中的數據,而不是「重新排序」它(這意味着改變行順序,但留下的列相同;使用該sortplyr::arrange)。


使用基R:

reshape(
    temperatures, 
    direction = "wide", 
    idvar  = "Day", 
    timevar = "Hour", 
    v.names = "Temperature" 
) 
+0

@JackRyan你也可以使用'factor(Hour,levels = paste0(formatC(0:23,flag =「0」,width = 2),「:00」))'手動重新確定因子。 –