0

I can't figure out why this is not working.

Have the following sample data:

MktAl   Orig    Dest
AA  BWI DFW
AA  BWI MIA
AA  CLE DFW
AA  CMH DFW
AA  DAY DFW
AA  DCA DFW
AA  DCA JFK
AA  DCA LAX
WN  RDU TPA
WN  BWI ATL
WN  BWI DFW
WN  BWI MIA
WN  BWI MCO

I am trying to reshape the data to get something like this:

ORIG    AA  WN
BWI DFW ATL
BWI MIA DFW
BWI NA  MIA
BWI NA  MCO
CLE DFW NA
CMH DFW NA
DAY DFW NA
DCA DFW NA
DCA JFK NA
DCA LAX NA
RDU NA  TPA

However, when I try to use the following command:

reshape(data=ks, direction="wide", timevar="MktAl", idvar="Orig")

I only get this:

Source: local data frame [6 x 2]

    Orig Dest.1:2
  (fctr)   (fctr)
1    BWI       NA
2    CLE       NA
3    CMH       NA
4    DAY       NA
5    DCA       NA
6    RDU       NA

Any idea why this is not working?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Carlos
  • 41
  • 4
  • Possible duplicate of [Reshape data from long to wide format R](http://stackoverflow.com/questions/5890584/reshape-data-from-long-to-wide-format-r) – zx8754 Jun 06 '16 at 19:48
  • You get a dplyr `tbl_df` from base R's `reshape()`? – Rich Scriven Jun 06 '16 at 19:53
  • Richard, I think that did it. I was tbl_dfing my data. I loaded the data again without applying it and it works. Any idea why it would have that behavior though? – Carlos Jun 06 '16 at 20:20
  • The 'table' function should do nicely. – IRTFM Jun 06 '16 at 20:27

2 Answers2

0

Whenever I was loading my data I was using tbl_df(mydata). Once I loaded it without this it worked fine.

Carlos
  • 41
  • 4
0

We need to create a sequence variable

library(dplyr)
library(tidyr)
df1 %>% 
  group_by(Orig) %>% 
  mutate(n = row_number()) %>% 
  spread(MktAl, Dest) %>% 
  select(-n)
#   Orig    AA    WN
#   <chr> <chr> <chr>
#1    BWI   DFW  <NA>
#2    BWI   MIA  <NA>
#3    BWI  <NA>   ATL
#4    BWI  <NA>   DFW
#5    BWI  <NA>   MIA
#6    BWI  <NA>   MCO
#7    CLE   DFW  <NA>
#8    CMH   DFW  <NA>
#9    DAY   DFW  <NA>
#10   DCA   DFW  <NA>
#11   DCA   JFK  <NA>
#12   DCA   LAX  <NA>
#13   RDU  <NA>   TPA
akrun
  • 874,273
  • 37
  • 540
  • 662