按组添加ID列

我希望根据纬度和经度两列在R中创建唯一ID,以便重复的位置具有相同的集群ID。


例如:


LAT        LONG    Cluster_ID

13.5330 -15.4180   1

13.5330 -15.4180   1

13.5330 -15.4180   1

13.5330 -15.4180   1

13.5330 -15.4170   2

13.5330 -15.4170   2

13.5330 -15.4170   2

13.5340 -14.9350   3

13.5340 -14.9350   3

13.5340 -15.9170   4

13.3670 -14.6190   5


狐的传说
浏览 579回答 3
3回答

慕妹3242003

.GRP加到data.table1.8.3,允许你做以下事情:# Your data, as a data.framedat <- read.table(text='LAT LONG13.5330 -15.4180&nbsp;13.5330 -15.4180&nbsp;13.5330 -15.4180&nbsp;13.5330 -15.4180&nbsp;13.5330 -15.4170&nbsp;13.5330 -15.4170&nbsp;13.5330 -15.4170&nbsp;13.5340 -14.9350&nbsp;13.5340 -14.9350&nbsp;13.5340 -15.9170&nbsp;13.3670 -14.6190', header=TRUE)# Convert it to a data.table# with keys as the combination of LAT and LONGlibrary(data.table)DT <- data.table(dat, key="LAT,LONG")DT[, Cluster_ID:=.GRP, by=key(DT)]DT#&nbsp; &nbsp; &nbsp; &nbsp; LAT&nbsp; &nbsp; LONG Cluster_ID#&nbsp; 1: 13.367 -14.619&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1#&nbsp; 2: 13.533 -15.418&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2#&nbsp; 3: 13.533 -15.418&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2#&nbsp; 4: 13.533 -15.418&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2#&nbsp; 5: 13.533 -15.418&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2#&nbsp; 6: 13.533 -15.417&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3#&nbsp; 7: 13.533 -15.417&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3#&nbsp; 8: 13.533 -15.417&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3#&nbsp; 9: 13.534 -15.917&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4# 10: 13.534 -14.935&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5# 11: 13.534 -14.935&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5
打开App,查看更多内容
随时随地看视频慕课网APP