我正在處理超過270,000個觀測值的三個變量dataset。這三個變量是觀測值,經度和緯度。在前面的,相關的,後我設法對如何使反向地理功能跳過缺失值,經度和緯度的觀測幫助:How to handle missing values when using a reverse geocode function?如何從我的反向地理編碼功能獲取ISO3代碼,而不是因子索引?
重複的例子:
Data <- data.frame(
Observation = 1:5,
Longitude = c(116.3880005, 53, -97, NA, NA),
Latitude = c(39.92890167, 32, 32, NA, NA))
下面的代碼工作。但是,它會爲每個國家生成因子索引,而不是我希望獲得的ISO3。
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
# 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 #would return the ISO3 code
}
#The function below fixes the NA error
coords2country_NAsafe <- function(points)
{
bad <- with(points, is.na(lon) | is.na(lat))
result <- character(length(bad))
result[!bad] <- coords2country(points[!bad,])
result
}
下產生因子索引(而不是ISO3代碼):
coords2country_NAsafe(points)
我想知道我可以修改我有上面的代碼中爲了輸出ISO3碼,而不是他們的因素指數。
你如何閱讀該點文件並將其傳遞給函數?爲什麼不簡單在這裏包括前10個點,並告訴我們你得到了什麼,以及你期望得到的國家?你確定你不只是混合拉長了嗎? – Spacedman
「超過27,000」是輕描淡寫。該數據文件中有257,388行。 – Spacedman
你好,對於觀察次數錯誤,我表示歉意。我肯定我沒有混淆經濟和經濟。我試圖完成的是在csv文件中插入一個新列,其中包含每個觀察值的相應ISO3代碼。 – ealfons1