如何透视表以在R中为可变行值创建列

use*_*551 5 pivot r reshape

我有一个包含列的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
Run Code Online (Sandbox Code Playgroud)

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

Store   Jan Feb Mar
A       100 150 120
B       200 230 320
Run Code Online (Sandbox Code Playgroud)

很感谢任何形式的帮助.我刚开始用R.

42-*_*42- 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)
Run Code Online (Sandbox Code Playgroud)

所以很可能你的月份列是一个按字母顺序排序的因素(编辑:)

> 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
Run Code Online (Sandbox Code Playgroud)

一个稍微不那么明显的方法(因为'I'函数返回其参数):

> with(df, tapply(Demand, list(Store, Month) , I)  )
  Jan Feb Mar
A 100 150 120
B 200 230 320
Run Code Online (Sandbox Code Playgroud)


Bti*_*rt3 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)
Run Code Online (Sandbox Code Playgroud)

作为参考,你应该看看这个很棒的教程.http://www.jstatsoft.org/v21/i12/paper