0

Forgive me if this is a repeated post, I have tried to search for this exact or at least similar scenario but did not have any luck.

I have data that is set up like so:

 id |start|year|place|sub place|
 -------------------------
 me |1    |1   |here |1  
 me |1    |2   |here |1
 me |1    |3   |here |1
 me |1    |4   |gone |2
 you|3    |3   |here |1
 you|3    |4   |gone |2
 you|3    |5   |gone |3

The row has an Id that is repeated for each year the Id is in the data. They also contain a column with the year in which they start repeated with the ID. Each row contains their location and their sub location. Their location can be one of two values and their sub place can be null if they finish early, or one of several values that they can move around within. The id's can only be in the data up to 4 times, but can be less than 4.

I would like to get the data set up in a wide format like this

 id |start|y1 place|y2 place|y3 place|y4 place|y1 sub|y2 sub|y3 sub|y4 sub
 me |1    |here    |here    |here    |gone    |1     |1     |1     |2
 you|3    |here    |gone    |gone    |        |1     |2     |3     |

I have been playing with reshape out of the tidyverse but I can't seem to manipulate it to produce something like this. Any guidance would be greatly appreciated.

alants
  • 3
  • 1
  • Look here: https://stackoverflow.com/questions/11608167/reshape-multiple-value-columns-to-wide-format – Nicolás Velasquez Feb 19 '18 at 20:47
  • Assuming `df` is your 5 column `data.frame`, try `require(tidyverse); df %>% gather(key, value, 4:5) %>% unite(year_key, year, key) %>% spread(year_key, value)`. – Maurits Evers Feb 19 '18 at 22:51
  • there are additional columns, they information contained in them is identical within an id, however. – alants Feb 23 '18 at 17:13

0 Answers0