Search code examples
rrowmultiple-columnsspread

How to convert row names to column names and bind it by order in r


I am working on a data set: Annual Returns by Ticker

and I want to convert to : Result Matrix

I used the code:

returns.df <- returns %>% spread(key = DATE, value = RETURN)

and its is showing wrong order: enter image description here


Solution

  • Assuming your long-form data starts with the rows in the order you want, try this:

    month_order = unique(returns)
    returns.df <- returns %>%
      spread(key = DATE, value = RETURN) %>% 
      select(c("TICKER", month_order))
    

    If your data doesn't begin in the right order, append a year and convert it to a Date class object. Then you can sort it to the right order and use the method above.