[R] Arranging column data to create plots

michael.reed at reagan.com michael.reed at reagan.com
Sun Jul 16 05:49:14 CEST 2017

Dear All,

I need some help arranging data that was imported.

The imported data frame looks something like this (the actual file is huge, so this is example data)

IDKey  X1  Y1  X2  Y2  X3  Y3  X4  Y4
Name1  21  15  25  10
Name2  15  18  35  24  27  45
Name3  17  21  30  22  15  40  32  55 

I would like to create a new data frame with the following

IDKey   X   Y
Name1  21  15
Name1  25  10
Name2  15  18
Name2  35  24
Name2  27  45
Name3  17  21
Name3  30  22
Name3  15  40
Name3  32  55

With the data like this I think I can do the following

ggplot(NewDF, aes(x=X, y=Y, color=IDKey) + geom_line

and get 3 lines with the various number of points.

The point is that each of the XY pairs is a data point tied to NameX.  I would like to rearrange the data so I can plot the points/lines by the IDKey.  There will be at least 2 points, but the number of points for each IDKey can be as many as 4.

I have tried using the gather() function from the tidyverse package, but I can't make it work.  The issue is that I believe I need two separate gather statements (one for X, another for Y) to consolidate the data.  This causes the pairs to not stay together and the data becomes jumbled.

Thanks for your help

Michael E. Reed

More information about the R-help mailing list