0

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

  • Just want to check: your complaint is the order of the columns in the result? – Gregor Thomas Apr 05 '19 at 20:45
  • Images do not provide a reproducible way to run the code. Please provide a reproducible example, see here https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 – cropgen Apr 05 '19 at 20:45

2 Answers2

0

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.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

I figured it out my writing these multiple lines:

column <- unique(returns$DATE)
ret <- matrix(returns$RETURN,nrow = 22,ncol = 60)
row <- unique(returns$TICKER)
rownames(ret) <- row
colnames(ret) <- column
ret

How about this one?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138