2011-06-24 30 views
5

我有一個data.frame,其中包含列:Month,Store和Demand。如何在表中創建列以創建列中的變量行

Month Store Demand 
Jan  A 100 
Feb  A 150 
Mar  A 120 
Jan  B 200 
Feb  B 230 
Mar  B 320 

我需要圍繞它轉動,使一個新data.frame或陣列列每個月,存儲例如: -

Store Jan Feb Mar 
A  100 150 120 
B  200 230 320 

任何幫助是非常讚賞。我剛開始與R.

回答

9
> df <- read.table(textConnection("Month Store Demand 
+ Jan  A 100 
+ Feb  A 150 
+ Mar  A 120 
+ Jan  B 200 
+ Feb  B 230 
+ Mar  B 320"), header=TRUE) 

那麼十有八九你的月柱與水平字母順序排序因素 (編輯:)

> df$Month <- factor(df$Month, levels= month.abb[1:3]) 
# Just changing levels was not correct way to handle the problem. 
# Need to use within a factor(...) call. 
> xtabs(Demand ~ Store+Month, df) 
     Month 
Store Jan Feb Mar 
    A 100 150 120 
    B 200 230 320 

稍微不太明顯的方法(因爲「我「函數返回其參數):

> with(df, tapply(Demand, list(Store, Month) , I) ) 
    Jan Feb Mar 
A 100 150 120 
B 200 230 320 
+0

有些東西在你的答案中打印輸出不太正確。例如,Jan A應該是100而不是150。你的代碼有效,所以我懷疑你在修改關卡之前複製了輸出。 –

+0

你對錯誤是正確的,但它是因爲我不正確地改變了關卡。往上看。 –

5

歡迎R.

使用R通常有很多方法可以達到同一目的。另一種方法是使用Hadley的重塑包。

# create the data as explained by @Dwin 
df <- read.table(textConnection("Month Store Demand 
           Jan  A 100 
           Feb  A 150 
           Mar  A 120 
           Jan  B 200 
           Feb  B 230 
           Mar  B 320"), 
       header=TRUE) 

# load the reshape package from Hadley -- he has created GREAT packages 
library(reshape) 

# reshape the data from long to wide 
cast(df, Store ~ Month) 

作爲參考,你應該看看這個偉大的教程。 http://www.jstatsoft.org/v21/i12/paper

+1

如果沒有重新排列不會給OP的要求的級別。 –

3

如果數據是在dat(和水平設置日曆順序),然​​後另一個基礎R解決方案是使用所述(令人難以置信的直觀)reshape()功能:

reshape(dat, v.names = "Demand", idvar = "Store", timevar = "Month", 
     direction = "wide") 

其中用於數據的片段給出:如果你想

> reshape(dat, v.names = "Demand", idvar = "Store", timevar = "Month", 
+   direction = "wide") 
    Store Demand.Jan Demand.Feb Demand.Mar 
1  A  100  150  120 
4  B  200  230  320 

名稱可以很容易地清洗:

> out <- reshape(dat, v.names = "Demand", idvar = "Store", timevar = "Month", 
+    direction = "wide") 
> names(out)[-1] <- month.abb[1:3] 
> out 
    Store Jan Feb Mar 
1  A 100 150 120 
4  B 200 230 320 

(要得到上面的輸出,我在一個類似的方式,在@迪文的回答顯示讀取的數據,然後運行以下:

dat <- transform(dat, Month = factor(Month, levels = month.abb[1:3])) 

其中dat就是我所謂的數據)

+0

+1只是爲了重申我在使用重塑功能時的挫折感。 –