This question already has an answer here:
I have the below data formed using code
test <- data.frame(dis = c(10,20,30,40),dur=c(30,40,60,90),method=c("car","car","Bicycle","Bicycle"),to_lon=c(-1.980,-1.5678,-1.324,-1.456),to_lat=c(55.3009,55.3416,55.1123,55.2234),from_lon=c(-1.4565,-1.3424,-1.4566,-1.1111),from_lat=c(76.8888,65.8999,76.9088,25.3344))
dis dur method to_lon to_lat from_lon from_lat
1 10 30 car -1.9800 55.3009 -1.4565 76.8888
2 20 40 car -1.5678 55.3416 -1.3424 65.8999
3 30 60 Bicycle -1.3240 55.1123 -1.4566 76.9088
4 40 90 Bicycle -1.4560 55.2234 -1.1111 25.3344
I want to convert this data frame such that it has one row for to_lat and to_lon and in the next row it has from_lat and from_lon. The rest of the details do not need to change and can be replicated. The desired result should be as below
dis dur method longitude latitude
from 10 30 car -1.98 55.3009
to 10 30 car -1.4565 76.8888
from 20 40 car -1.5678 55.3416
to 20 40 car -1.3424 65.8999
from 30 60 Bicycle -1.324 55.1123
to 30 60 Bicycle -1.4566 76.9088
from 40 90 Bicycle -1.456 55.2234
to 40 90 Bicycle -1.1111 25.3344
Any help will be much appreciated.
Thanks.
We can use
melt
fromdata.table
which can take multiplemeasure
columns.This may not be the most elegant solution, but it should work and is hopefully understandable:
We split the data into two dataframes: one with the 'from' longitude and latitude data (call it testF) and the other with the 'to' data (call it test). We then use rbind to insert the rows of 'testF' in the appropriate places in 'test'.
Here is an alternative approach using package
tidyr
(a popular package for data munging), which avoidsfor
loop.