[R] reordering a data.frame

Marc Schwartz MSchwartz at MedAnalytics.com
Thu May 5 16:22:30 CEST 2005


On Fri, 2005-05-06 at 15:26 +0200, Achaz von Hardenberg wrote:
> Hi,
> I have a data.frame which looks like this:
>   
> id     est0     est1	est2	est3	est4	est5	est6    est7
>  1   	1	2	3	1	7	9	3	4
>  2	4	1	1	7	6	5	1	2  
> [...]
> 
> 
> I would like to reorder it to obtain the following:
> 
> id  	est	VALUE
> 1	0	1
> 1	1	2
> 1	2	3
> 1	3	1
> 1	4	7
> 1	5	9
> 1	6	3
> 1	7	4
> 2	0	4
> 2	1	1
> 2	2	1
> 2	3	7
> 2	4	6
> 2	5	5
> 2	6	1
> 2	7	2
> [...]
> 	
> Can anybody help me out?
> 
> Thanks in advance!
> 
> Achaz

Here is one approach, with your data in 'df' from read.table():

# use reshape()
df.new <- reshape(df, direction = "long", idvar = "id", 
                  varying = list(names(df[2:9])), times = 0:7)

# use order() for row sequence
> df.new <- df.new[order(df.new$id, df.new$time), ]

# set colnames as above
> colnames(df.new) <- c("id", "est", "VALUE")

> df.new
    id est VALUE
1.1  1   0     1
1.2  1   1     2
1.3  1   2     3
1.4  1   3     1
1.5  1   4     7
1.6  1   5     9
1.7  1   6     3
1.8  1   7     4
2.1  2   0     4
2.2  2   1     1
2.3  2   2     1
2.4  2   3     7
2.5  2   4     6
2.6  2   5     5
2.7  2   6     1
2.8  2   7     2


Note that the rownames above are sequenced from the original 1:2.

See ?reshape for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list