我目前正在使用R中的数据(271,848的N),如下所示:
Observation Longitude Latitude
--------------------------------------
1 116.38800 39.928902
2 53.000000 32.000000
3 NA NA
4 NA NA
我正在使用以下帖子中的反向地理编码函数:在 R 中将纬度和经度坐标转换为国家/地区名称
当我运行< code > coords 2 country(points)行时,我得到以下错误:
". check NumericCoerce2bean(obj):非有限坐标中的错误"
我的最佳猜测是该函数不知道如何处理丢失的值。当我对观察值的子集(不包括NA/缺失值)运行代码时,它工作了。
我试图稍微修改这个函数(见下面的最后一行)来解决这个问题,但这仍然产生了我上面提到的错误。
可重现的示例:
Data <- data.frame(
Observation = 1:5,
Longitude = c(116.3880005, 53, -97, NA, NA),
Latitude = c(39.92890167, 32, 32, NA, NA))
library(sp)
library(rworldmap)
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat +datum=wgs84"))
#! andy modified to make the CRS the same as rworldmap
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
# new changes in worldmap means you have to use this new CRS (bogdan):
pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#The line below is what I thought could resolve the problem.
na.action = na.omit
}
最好用这个代替:
coords2country_NAsafe <- function(points)
{
bad <- with(points, is.na(lon) | is.na(lat))
result <- character(length(bad))
result[!bad] <- coords2country(points[!bad,])
result
}