我试图使用以下代码更改县名正确命名,即alcona
,而不是michigan,alcona
。
michigan.map <- map("county", 'michigan',plot=FALSE, fill = TRUE)
michigan.map$names
IDs <- sapply(strsplit(michigan.map$names, ":"), function(x) x[1])
michigan.sp <- map2SpatialPolygons(michigan.map, IDs = IDs,
proj4string = CRS("+proj=longlat +ellps=WGS84"))
plot(michigan.sp)
names(michigan.sp)
names(michigan.sp) <- sapply(strsplit(names(michigan.sp), ","), function(x) x[2])
它给了我:
“名称错误(michigan.sp)&lt; - sapply(strsplit(names(michigan.sp),”,“),: class'SpiftialPolygons'没有'名字'插槽“。
我不确定为什么因为它有名字槽。
另外作为一个附带问题,ID行在代码中做了什么?
答案 0 :(得分:1)
我的评论显示了如何解决您正在做的事情,但为什么不进一步使用更现代/准确的县界?
library(sp)
library(rgdal)
library(tigris) #devtools::install_github("walkerke/tigris")
mi <- counties("michigan", detailed=FALSE)
head(mi@data)
## STATEFP COUNTYFP COUNTYNS AFFGEOID GEOID NAME LSAD ALAND AWATER
## 141 26 041 01622963 0500000US26041 26041 Delta 06 3033127269 2124385360
## 142 26 047 01622966 0500000US26047 26047 Emmet 06 1210886745 1073476051
## 143 26 097 01622991 0500000US26097 26097 Mackinac 06 2646869250 2793795315
## 144 26 141 01623013 0500000US26141 26141 Presque Isle 06 1706067776 4957327559
## 145 26 153 01623017 0500000US26153 26153 Schoolcraft 06 3033812509 1845664188
## 146 26 163 01623022 0500000US26163 26163 Wayne 06 1585109570 157120883
plot(mi)
答案 1 :(得分:0)
michigan.map <- map("county", 'michigan',plot=FALSE, fill = TRUE)
IDs <- sapply(strsplit(michigan.map$names, ","), function(x) x[2])
michigan.sp <- map2SpatialPolygons(michigan.map, IDs = IDs,
proj4string = CRS("+proj=longlat +ellps=WGS84"))
names(michigan.sp)
我认为这段代码符合你的要求......它并没有完全回答你的问题。必须有一种方法可以在创建后设置sp对象的ID,但名称&lt; - 不是它。
答案 2 :(得分:0)
str(michigan.sp)
是你的朋友;滚动查看结果,您会看到确实没有插槽names
。至少对我来说,更容易和更清楚的是改变michigan.map
michigan.map$names <- gsub('michigan,' ,'', michigan.map$names)
michigan.map$names
[1] "alcona" "alger" "allegan" "alpena" "antrim"
[6] "arenac" "baraga" "barry" "bay" "benzie"
[11] "berrien" "branch" "calhoun" "cass" "charlevoi"
[16] "cheboygan" "chippewa" "clare" "clinton" "crawford"
[21] "delta" "dickinson" "eaton" "emmet" "genesee"
[26] "gladwin" "gogebic" "grand traverse" "gratiot" "hillsdale"
[31] "houghton" "huron" "ingham" "ionia" "iosco"
[36] "iron" "isabella" "jackson" "kalamazoo" "kalkaska"
[41] "kent" "keweenaw" "lake" "lapeer" "leelanau"
[46] "lenawee" "livingston" "luce" "mackinac" "macomb"
[51] "manistee" "marquette" "mason" "mecosta" "menominee"
[56] "midland" "missaukee" "monroe" "montcalm" "montmorency"
[61] "muskegon" "newaygo" "oakland" "oceana" "ogemaw"
[66] "ontonagon" "osceola" "oscoda" "otsego" "ottawa"
[71] "presque isle" "roscommon" "saginaw" "st clair" "st joseph"
[76] "sanilac" "schoolcraft" "shiawassee" "tuscola" "van buren"
[81] "washtenaw" "wayne" "weford"