R:将坐标转换为 "Trips"

R: Converting Coordinates into "Trips"

我正在使用 R 编程语言。

我有以下数据框,其中包含有序城市列表的纬度和经度:

map_data <- data.frame("Lat" = c(43.5426, 43.2424, 43.6544, 43.6452, 43.6629), "Long" = c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957 ), id = c(1,2,3,4,5))

map_data$id = as.factor(map_data$id)

      Lat     Long id
1 43.5426 -79.3871  1
2 43.2424 -79.3860  2
3 43.6544 -79.3807  3
4 43.6452 -79.3806  4
5 43.6629 -79.3957  5

我想将此数据框转换成以下格式:

  start_lat start_long end_lat end_long
1   43.5426   -79.3871 43.2424  -79.386
2   43.2424   -79.3860 43.6540  -79.386

在上面的数据框中:

目前,我在 Microsoft Excel 中手动执行此操作 - 我只有几个城市,因此我可以手动管理它。

但是有人可以告诉我如何对大量数据执行此操作吗?

谢谢!

使用data.table

library(data.table)

result=setDT(map_data)[
  , c("end_lat","end_long"):= shift(map_data[,c(1,2)],-1)][
    , .(id, start_lat = Lat, start_long=Long, end_lat,end_long)]

result[.N, c("end_lat", "end_long"):=result[1,.(start_lat,start_long)]]

输出:

       id start_lat start_long end_lat end_long
   <fctr>     <num>      <num>   <num>    <num>
1:      1   43.5426   -79.3871 43.2424 -79.3860
2:      2   43.2424   -79.3860 43.6544 -79.3807
3:      3   43.6544   -79.3807 43.6452 -79.3806
4:      4   43.6452   -79.3806 43.6629 -79.3957
5:      5   43.6629   -79.3957 43.5426 -79.3871 

如果您愿意,这里有一个 baseR 方法:

result = rbind(
  cbind(map_data[1:nrow(map_data)-1,c(1,2)], map_data[-1,c(1,2)]),
  cbind(map_data[nrow(map_data), c(1,2)], map_data[1,c(1,2)])
)
colnames(result) <- c("start_lat", "start_long", "end_lat", "end_long")

输出

  start_lat start_long end_lat end_long
1   43.5426   -79.3871 43.2424 -79.3860
2   43.2424   -79.3860 43.6544 -79.3807
3   43.6544   -79.3807 43.6452 -79.3806
4   43.6452   -79.3806 43.6629 -79.3957
5   43.6629   -79.3957 43.5426 -79.3871