I have created a table in R by merging data, which currently looks like the example below. The key thing here is that I have 3 rows for every ID: AM, IP and PM.
ID | Time | Speed |
---|---|---|
101 | AM | 8 |
101 | PM | 6 |
101 | IP | 9 |
102 | N/A | N/A |
102 | N/A | N/A |
102 | N/A | N/A |
103 | AM | 7 |
103 | IP | 6 |
103 | PM | 8 |
I want to convert this to a table where there is only 1 row for each ID and the corresponding data is stored in columns, i.e. like this:
ID | Time.x | Speed.x | Time.y | Speed.y | Time.z | Speed.z |
---|---|---|---|---|---|---|
101 | AM | 8 | PM | 6 | IP | 9 |
102 | N/A | N/A | N/A | N/A | N/A | N/A |
103 | AM | 7 | PM | 6 | IP | 8 |
I have gone about this so far by filtering the table in to 3 tables, i.e. so I have an AM, an IP and a PM table. Then I have merged AM to IP to produce an "AMIP" table, which I have then merged with PM to create the final table.
The problem with this is that where I have no data, such as for ID 103, this is then lost during the filtering process and I end up with this:
ID | Time.x | Speed.x | Time.y | Speed.y | Time.z | Speed.z |
---|---|---|---|---|---|---|
101 | AM | 8 | PM | 6 | IP | 9 |
103 | AM | 7 | PM | 6 | IP | 8 |
By the way, please note that sometimes there may be data for AM but not IP or PM, or any of those combinations, so for example the following could also be possible as the starting data:
ID | Time | Speed |
---|---|---|
101 | AM | 8 |
101 | PM | 6 |
101 | IP | 9 |
102 | N/A | N/A |
102 | PM | 8 |
102 | N/A | N/A |
103 | AM | 7 |
103 | IP | 6 |
103 | PM | 8 |
If someone could please advise how best I can convert the table whilst retaining all ID's I would be very grateful.