我正在使用 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
在上面的資料框中:
- 第一行代表從“城市1到城市2”的“旅行”
- 第二行代表從“城市2到城市3”的“旅行”
- 等等。
目前,我在 Microsoft Excel 中手動執行此操作 - 我只有幾個城市,因此我可以手動管理。
但是有人可以告訴我如何處理大量資料嗎?
謝謝!
uj5u.com熱心網友回復:
采用data.table
library(data.table)
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)]
輸出:
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 NA NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430458.html
下一篇:繪制一段時間內的財務/投資價值
