如果數據是在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
就是我所謂的數據)
有些東西在你的答案中打印輸出不太正確。例如,Jan A應該是100而不是150。你的代碼有效,所以我懷疑你在修改關卡之前複製了輸出。 –
你對錯誤是正確的,但它是因爲我不正確地改變了關卡。往上看。 –