I have imported a table (Table1) in the following format:
ID Name Age Start Status1 Status2 Status3 Status4 Status5 Status6
01 John 45 2011 25 13 13 12 34 35
02 Mike 23 2017 12 15 18 45 32 25
03 Peter 34 2019 34 12 15 19 24 27
04 Sarah 21 2020 45 46 47 48 49 50
And I have generated another table (Table2) that looks like this:
ID Name Age Start Year Value
02 Mike 23 2017 3 24
03 Peter 34 2019 1 11
03 Peter 34 2019 2 13
03 Peter 34 2019 3 13
04 Sarah 21 2020 1 42
04 Sarah 21 2020 2 43
04 Sarah 21 2020 3 44
Table2 contains predicted Values for the first 3 years after and including Start, BUT only if three years have not passed yet (as at the current year, 2019). So in the above example, ID 01 is already more than 3 years passed their Start value so have no predictions; ID 02 is two years passed their Start value so has one prediction; IDs 03 and 04 are zero years passed their Start value so have three predictions.
I need to transpose the Values from Table2 into Table1, replacing the Status values and shifting them to the right. The final table should look like this:
ID Name Age Start Status1 Status2 Status3 Status4 Status5 Status6
01 John 45 2011 25 13 13 12 34 35
02 Mike 23 2017 24 12 15 18 45 32
03 Peter 34 2019 11 13 13 34 12 15
04 Sarah 21 2020 42 43 44 45 46 47
As you can hopefully see, the row for ID 01 remains unchanged. For ID 02, the old Status values have shifted one to the right, and Status1 has been replaced. For IDs 03 and 04, the old Status values have shifted three places to the right, and Status1 to Status3 have been replaced. As you can see, the old values that were in Status4 to Status6 have been removed.
I am quite stuck with this. So far I have tried to make some rules around the replacements as follows:
1) If Year is more than 3 years from the current year (2019), then leave the Status column names as they are. e.g. row 1 of Table1.
2) If Start is 2019 or greater, rename the Status columns by adding 3. e.g in rows 3 and 4 of Table1, Status1 should be renamed Status4, and so on. The last 3 Status columns (Status4 to Status6) would be deleted.
3) If Start is within 3 years of 2019 (i.e. 2017 to 2019), then rename the Status columns by adding the difference between 2016 and Start. e.g. in row 2 of Table1, Status1 would be renamed Status2 and so on. The last column (Status6) would be deleted.
I could code these using if / else, but I'm not sure how to fit these within a data wrangling pipe with select() and left_join() to carry out these changes successfully. I am using R, but could use SQL too if it was easier. Any help would be much appreciated.
p.s. I appreciate that the resulting table is in a strange format, but unfortunately that is what I need to produce.