我有一个包含以下列的 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。
最佳答案
> 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)
所以很可能你的 Month 列是一个按字母顺序排序的因素
(编辑:)
> 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
一个不太明显的方法(因为 'I' 函数返回它的参数):
> with(df, tapply(Demand, list(Store, Month) , I) )
Jan Feb Mar
A 100 150 120
B 200 230 320
关于r - 如何透视表以从 R 中的可变行值创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6471226/