I am trying to reshape my data from this form in exhibit A to the form in exhibit B. I’ve tried reshape and looping over the data by each three columns and appending the datasets, but can’t quite get there. How can I reshape this?
A AFG1 AFG2 AFG3 US1 US2 US3 t
5 7 9 3 4 5 1980
6 8 10 4 6 5 2000
B 1 2 3 t xtry
5 7 9 1980 AFG
6 8 10 2000 AFG
3 4 5 1980 US
4 6 5 2000 US
Assuming your
data.frameis called “mydf”, try this:For your problem, you have to be a little more verbose in your arguments than a straightforward
reshapeproblem because your variables are named differently than what R expects (which is in the form of1.AFG,2.AFG, and so on).For example:
If your names looked like the following:
The
reshapecommand is a bit more direct.reshape2
If you are looking for a “reshape2” solution, I actually find it a little more work than using base R’s
reshapefunction (it’s usually the other way around). Here’s what I came up with:First,
meltthe dataset.That “variable” column is pretty useless to us in its current form, so let’s fix it.
Here’s what the data look like now.
Now comes the easy part.