[R] How to transform: 4 columns into two columns stacked

Ralf B ralf.bierig at gmail.com
Fri Jul 16 13:27:18 CEST 2010


I have the following data structure:

n=5
mydata <- data.frame(id=1:n, x=rnorm(n), y=rnorm(n), id=1:n,
x=rnorm(n), y=rnorm(n))
print(mydata)

producing the following represention

id          x           y id.1       x.1        y.1
1  1  0.5326855 -2.07633703    1 0.7930274 -1.0530558
2  2  0.7888909  0.63354693    2 0.5908323 -1.3543282
3  3  0.5350803 -0.20108931    3 2.5079242 -0.4657274
4  4 -1.3041960 -0.25195129    4 1.6294046 -1.4094830
5  5  0.3109767 -0.02305981    5 0.5183756  1.3084776


however I need to transform this data into this form:

    id          x           y
1  1  0.5326855 -2.07633703
2  2  0.7888909  0.63354693
3  3  0.5350803 -0.20108931
4  4 -1.3041960 -0.25195129
5  5  0.3109767 -0.02305981
6  1 0.7930274 -1.0530558
7  2 0.5908323 -1.3543282
8  3 2.5079242 -0.4657274
9  4 1.6294046 -1.4094830
10 5 0.5183756  1.3084776

what is the simplest way to do that?

Thanks a lot in advance!
Ralf



More information about the R-help mailing list