使用tm_shape提示找不到'Afghanistan'对象,但对象实际存在的问题求助
问题
尝试用tmap结合rnaturalearth的shapefile绘制各国人权指数地图,合并数据后执行tm_shape(Afghanistan) + tm_fill()时出现错误:
Error in as.list.environment(environment()) : object 'Afghanistan' not found
相关代码流程:
- 下载rnaturalearth数据:
install.packages("rnaturalearth") install.packages("rnaturalearthdata") library(rnaturalearth) library(rnaturalearthdata) country50 <- ne_download(scale = 50, type = 'countries', category = 'cultural')
- 合并shapefile与人权数据框:
ciri2014.country50.merged = merge(country50, CIRI_Data_1981_2011_2014_04_14, by = 'NAME_LONG', duplicateGeoms = TRUE)
- 转换为sf对象后仍报错:
sf.ciri2014.country50.merged = st_as_sf(ciri2014.country50.merged) tm_shape(Afghanistan) + tm_fill() # 报错找不到对象
问题原因
tmap::tm_shape()要求传入空间对象(sf/sp类),而非直接传入国家名称字符串。你误以为可以像tmap自带的nz/world那样直接用国家名调用对象,但实际上Afghanistan并不是当前环境中存在的空间对象,只是合并数据框里的一个国家名称值,因此R会报错找不到该对象。
解决办法
1. 从合并后的sf数据框中筛选目标国家的空间数据
先从sf.ciri2014.country50.merged中提取阿富汗的空间子集,再传入tm_shape:
# 筛选阿富汗的空间数据 afghanistan_sf <- sf.ciri2014.country50.merged[sf.ciri2014.country50.merged$NAME_LONG == "Afghanistan", ] # 绘制地图 tm_shape(afghanistan_sf) + tm_fill()
2. 验证数据合并的正确性
如果筛选后没有结果,检查NAME_LONG列的匹配情况:
- 查看合并后数据框中
NAME_LONG的取值,确认是否存在拼写不一致(比如大小写、空格差异):
unique(sf.ciri2014.country50.merged$NAME_LONG)
- 若存在匹配问题,调整合并的键值,或者先统一两个数据框中国家名称的格式。
3. 全局地图高亮目标国家
如果需要在全球地图中高亮阿富汗,可直接使用全局sf对象,通过tm_fill参数实现:
tm_shape(sf.ciri2014.country50.merged) + tm_fill(col = ifelse(NAME_LONG == "Afghanistan", "red", "lightgray"), legend.show = FALSE)
内容的提问来源于stack exchange,提问作者Mary Lind
相关产品推荐
相关产品推荐

