PDA

View Full Version : Re-organising a data frame



Jimdare
01-08-2009, 09:36 PM
Hi again,

I have another Issue. I have the following data frame that I want to reorgainse into the 2 data frames at the very bottom. Does anyone know how to do this or where I could learn how to do this?

Original Data Frame:

Year Species Stock Catch
2001 ORH OR1 4687
2002 ORH OR1 3215
2003 ORH OR1 6782
2001 ORH OR2 4687
2002 ORH OR2 3215
2003 ORH OR2 6782
2001 SNA SNA1 19
2002 SNA SNA1 116
2003 SNA SNA1 106
2001 SNA SNA2 757
2002 SNA SNA2 1778
2003 SNA SNA2 3576

Desired Frames

ORH
Year OR1 OR2
2001 4687 4687
2002 3215 3215
2003 6782 6782

SNA
Year SNA1 SNA2
2001 19 757
2002 116 1778
2003 106 3576

vinux
01-09-2009, 08:03 AM
Hi Jim
Use "reshape" package.


reshape(<parent dataset>,timevar="Stock",idvar="Year",direction="wide")
Then you can split it into two datasets.

unstack function also can be used. But it may not work always.

Regards
Richie

Tart
01-09-2009, 11:41 AM
reshape is probably that you want. But you may try function split (there is also unsplit version). It is not exactly what you need but close. I really like this function and would have a hard time without it, so this is why I advocate it ;-)


#x.orig - original data
x.new <- split(x.orig, x.orig$Species)
x.new

$ORH
Year Species Stock Catch
1 2001 ORH OR1 4687
2 2002 ORH OR1 3215
3 2003 ORH OR1 6782
4 2001 ORH OR2 4687
5 2002 ORH OR2 3215
6 2003 ORH OR2 6782

$SNA
Year Species Stock Catch
7 2001 SNA SNA1 19
8 2002 SNA SNA1 116
9 2003 SNA SNA1 106
10 2001 SNA SNA2 757
11 2002 SNA SNA2 1778
12 2003 SNA SNA2 3576


You can split x.new and so on.