如何旋转表格以在 R 中从可变行值生成列表格

由网友(我会认为你是个疯子 ぺ)分享简介:我有一个包含以下列的 data.frame:Month、Store 和 Demand.I have a data.frame with the columns: Month, Store and Demand.Month Store DemandJan A 100Feb A 15...

我有一个包含以下列的 data.frame:Month、Store 和 Demand.

I have a data.frame with the columns: Month, Store and Demand.

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

我需要旋转它以创建一个新的 data.frame 或数组,每个月都有列,存储例如:

I need to pivot it around to make a new data.frame or array with columns for each month, store e.g.:

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

非常感谢任何帮助.我刚开始使用 R.

Any help is very much appreciated. I have just started with 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)

因此,您的月份"列很可能是一个按字母顺序排序的因素()

So in all likelihood your Month column is a factor with levels sorted alphabetically ()

> 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'函数返回它的参数):

A slightly less obvious method (since the 'I' function returns its argument):

> with(df, tapply(Demand, list(Store, Month) , I)  )
  Jan Feb Mar
A 100 150 120
B 200 230 320
阅读全文

相关推荐

最新文章