R 查找多个位置的匹配坐标
我有数百个城市的坐标。从气候模型数据中,我想找到离我的城市最近的坐标。我可以使用下面的代码为每个城市单独执行此操作,但必须有一种更简单的方法为所有城市执行此操作,而不是像下面那样列出每个城市R 查找多个位置的匹配坐标,r,R,我有数百个城市的坐标。从气候模型数据中,我想找到离我的城市最近的坐标。我可以使用下面的代码为每个城市单独执行此操作,但必须有一种更简单的方法为所有城市执行此操作,而不是像下面那样列出每个城市 # Resolution of climate model data OBS.lat = seq(-90, 90, 0.5) OBS.lon = seq(-180, 180, 0.5) # Set coordinates for cities BERLlat = 52.52 BERLlon = 13.39
# Resolution of climate model data
OBS.lat = seq(-90, 90, 0.5)
OBS.lon = seq(-180, 180, 0.5)
# Set coordinates for cities
BERLlat = 52.52
BERLlon = 13.39
BERNlat = 46.95
BERNlon = 7.45
BUElat = -34.60
BUElon = -58.38
BERL.lat=which.min(abs(OBS.lat-BERLlat))
BERL.lon=which.min(abs(OBS.lon-BERLlon))
BERN.lat=which.min(abs(OBS.lat-BERNlat))
BERN.lon=which.min(abs(OBS.lon-BERNlon))
BUE.lat=which.min(abs(OBS.lat-BUElat))
BUE.lon=which.min(abs(OBS.lon-BUElon))
我同意一些评论,即使用
sf
软件包(以及其他地理空间软件包)可能对这类活动有意义。然而,要直接用base R和您已有的设置回答您的问题,一步改进是将which.min(abs())
调用放入实际函数中,并使用lappy
为您进行迭代,这还需要将城市坐标和名称放入向量和/或数据帧中
# Resolution of climate model data
OBS.lat = seq(-90, 90, 0.5)
OBS.lon = seq(-180, 180, 0.5
# set the city names and coordinates into vectors instead
city_names <- c("BERL","BERN","BUE")
city_lat <- c(52.52, 46.95, -34.60)
city_long <- c(13.39, 7.45, -58.38)
# define a local function to find coordinates
find_dist <- function(x, obs) {
return(which.min(abs(obs-x)))
}
# do the iteration with the lapply function and unlist the results
lats <- unlist(lapply(city_lat,find_dist,OBS.lat))
lons <- unlist(lapply(city_long,find_dist,OBS.lon))
# put into a data frame for viewing
data.frame(city_names, lats, lons)
你用过吗?没有,但是谢谢@camille-我会看看。类似的帖子:,,可能是重复的
## Output - same results as in your code
# city_names lats lons
# 1 BERL 286 388
# 2 BERN 275 376
# 3 BUE 112 244