如果数据在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
(为了获得上面的输出,我以与@DWin's Answer 中所示类似的方式读取数据,然后运行以下命令:
dat <- transform(dat, Month = factor(Month, levels = month.abb[1:3]))
dat
我所说的数据在哪里)