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

∥☆過路亽.° 提交于 2019-12-08 11:46:30

问题


Short version: when executing the following command qtm(World, "amount") I get the following error message:

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

Disclaimer: this is the same problem I used to have in this question, but if I'm not wrong, in that one the problem was that I had one variable on the left dataframe that matched to several variables on the right one, and hence, I needed to group variables on right dataframe. In this case, I am pretty sure that I do not have the same problem, as can be seen from the code below:

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")

My guess is that the clue may be the fact that the column I am using when joining both dataframes has different levels (hence it is converted to string), but I'm ashamed to admit that I still don't understand the error that I am having here. I'm assuming I have something wrong with my dataframe, although I have to admit that it didn't work even with a smaller dataframe:

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")

Can anyone help me pointing out what's causing this error (providing an solution may also be much appreaciated)


回答1:


Edited: It is again your data

table(df$iso_a3)


来源:https://stackoverflow.com/questions/46430561/how-to-join-spatial-data-with-dataframe-so-it-can-be-displayed-with-tmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!