【发布时间】:2015-07-13 19:00:29
【问题描述】:
我浏览了许多论坛帖子,但没有找到答案。我有一个大的纬度和经度列表,并想制作一个网格,并基于该网格为每对纬度/经度分配一个来自该网格的单元格引用。最终我想根据单元格引用分配值。例如。 Lat 39.5645 和 long -122.4654 属于网格单元格参考 1,该单元格中的谋杀总数为 16,袭击总数为 21。有更好的方法可以做到这一点,但这是我所知道的唯一方法。
#number of segments, this determines size of grid
segments <- 5
#use these to dvide up the arrays
Xcounter <-(max(cleantrain$X)-min(cleantrain$X))/segments
Ycounter <-(quantile (cleantrain$Y,.9999)-min(cleantrain$Y))/segments
#arrays created from the counter and lat and longs
Xarray <- as.data.frame(seq(from=min(cleantrain$X), to=max(cleantrain$X), by=Xcounter))
Yarray <-as.data.frame(seq(from=min(cleantrain$Y), to=quantile(cleantrain$Y,.9999), by=Ycounter))
#the max for the latitude is 90 but the .9999 percentile is ~39,
# but I still want the grid to include the 90
Yarray[6,1]<-max(cleantrain$Y)
#create dummy column so I know what the values shouldn't be when I print the results
cleantrain$Area <- seq(from =1, to=nrow(cleantrain), by =1)
#for loop that goes through once for each row in my data
for (k in 1:100) {
#this loop goes through the longitudes
for (i in 1:seg-1) {
#this loop goes though the latitudes
for (j in 1:seg-1){
#should check if the row fits into that grid
if(cleantrain$Y[k] < Yarray[(j+1),1] &&
cleantrain$X[k] < Xarray[(i+1),1] &&
cleantrain$Y[k] >= Yarray[j,1] &&
cleantrain$X[k] >= Xarray[i,1]){
#writes to the row the cell reference
cleantrain$Area[k] <- ((i-1)*segments+j)
}
}
}
}
#check the results
cleantrain$Area[1:100]
如果您只将 i 值写入cleantrain$Area,它将始终打印 1 而不是 1-5。但是 j for 循环会像预期的那样打印 1-5 。但是,如果您进入 if 语句并切换 i 和 j 循环引用,j 将始终为 1,而 i 将始终为 1-5。
这是我的数组值
#Yarray
1 37.70788
2 37.73030
3 37.75272
4 37.77514
5 37.79756
6 37.81998
#Xarray
1 -122.5136
2 -122.1109
3 -121.7082
4 -121.3055
5 -120.9027
6 -120.5000
编辑:
这是前 10 个经纬度:
cleantrain$Y[1:10]
[1] 37.77460 37.77460 37.80041 37.80087 37.77154 37.71343 37.72514 37.72756 37.77660 37.80780
cleantrain$X[1:10]
[1] -122.4259 -122.4259 -122.4244 -122.4270 -122.4387 -122.4033 -122.4233 -122.3713 -122.5082 -122.4191
【问题讨论】:
标签: r if-statement for-loop latitude-longitude