0

I am new to "R", I need to convert rows to columns Source is saved in data frame

What i am able to do

destination<- as.data.frame.matrix(xtabs(~order_id+dish_id, source))

But , i unable to get what i desired So can any1 help me to get data like in destination

Source:-

order_id    primary_dish    dish_id  category_id
328507       38118            38114   1536
328523       38081            38068   1829
328523       38094            38068   1829

(Source data looks in above format)

Destination :-

order_id    primary_dish    38114   38068   1536   1829
328507        38118           1       0       1     0
328523        38081           0       1       0     1
328523        38094           0       1       0     1
r2evans
  • 141,215
  • 6
  • 77
  • 149
ankitkhanduri
  • 315
  • 1
  • 2
  • 9
  • Are you trying to transpose? If yes, try t(dataframe) – user2510479 May 24 '17 at 18:11
  • Possible duplicate of [How to reshape data from long to wide format?](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – jogo May 24 '17 at 18:13
  • In order to use that "long-to-wide" link @jogo provided, you'll want to first go from "wide-to-long", effectively combining `category_id` and `dish_id` into a single column. Then you can easily convert from "long-to-wide" as already suggested. – r2evans May 24 '17 at 18:16

1 Answers1

0

Something like this may work to get you the desired output.

library (dplyr)
library (tidyr)
destination <- destination %>%
    mutate (dval = 1) %>%
    spread (key = dish_id, value = dval, fill = 0) %>%
    mutate (cval = 1) %>%
    spread (key = category_id, value = cval, fill = 0) %>%
    arrange (order_id, primary_dish)
Matt Jewett
  • 3,249
  • 1
  • 14
  • 21