如何将空间数据与 Dataframe 连接起来,以便用 Tmap 显示?

How to join Spatial data with Dataframe so it can be displayed with Tmap?

简短版本: 执行以下命令时 qtm(World, "amount") 我收到以下错误消息:

Error in $<-.data.frame(*tmp*, "SHAPE_AREAS", value = c(653989.801201595, : replacement has 177 rows, data has 175

免责声明: 这与我以前在 中遇到的问题相同,但如果我没记错的话,那个问题就是我遇到的左侧数据框中的一个变量与右侧数据框中的多个变量相匹配,因此,我需要对右侧数据框中的变量进行分组。在这种情况下,我很确定我没有遇到同样的问题,从下面的代码可以看出:

library(tmap)
library(tidyr)

# Read tmap's world map.
data("World")

# Load my dataframe.
df = read.csv("https://gist.githubusercontent.com/ccamara/ad106eda807f710a6f331084ea091513/raw/dc9b51bfc73f09610f199a5a3267621874606aec/tmap.sample.dataframe.csv",
         na = "")

# Compare the countries in df that do not match with World's
# SpatialPolygons.
df$iso_a3 %in% World$iso_a3

# Return rows which do not match
selected.countries = df$iso_a3[!df$iso_a3 %in% World$iso_a3]


df.f = filter(df, !(iso_a3 %in% selected.countries))

# Verification.
df.f$iso_a3[!df.f$iso_a3 %in% World$iso_a3]

World@data = World@data %>%
  left_join(df.f, by = "iso_a3") %>%
  mutate(iso_a3 = as.factor(iso_a3)) %>%
  filter(complete.cases(iso_a3))

qtm(World, "amount")

我的猜测是,线索可能是我在连接两个数据帧时使用的列具有不同的级别(因此它被转换为字符串),但我很惭愧地承认我仍然没有了解我在这里遇到的错误。我假设我的数据框有问题,尽管我不得不承认即使使用较小的数据框它也不起作用:

selected.countries2 = c("USA", "FRA", "ITA", "ESP")
df.f2 = filter(df, iso_a3 %in% selected.countries2)
df.f2$iso_a3 = droplevels(df.f2$iso_a3)

World@data = World@data %>%
  left_join(df.f2, by = "iso_a3") %>%
  mutate(iso_a3 = as.factor(iso_a3)) %>%
  filter(complete.cases(iso_a3))

World$iso_a3 = droplevels(World$iso_a3)

qtm(World, "amount")

谁能帮我指出是什么导致了这个错误(提供解决方案也很感激)

已编辑:又是你的数据

table(df$iso_a3)