如何将空间数据与Dataframe结合在一起,以便可以与Tmap一起显示? [英] How to join Spatial data with Dataframe so it can be displayed with Tmap?
问题描述
简短版本::执行以下命令qtm(World, "amount")
时,出现以下错误消息:
Short version: when executing the following command qtm(World, "amount")
I get the following error message:
$<-.data.frame
中的错误(*tmp*
,"SHAPE_AREAS",值= c(653989.801201595,:替换具有177行,数据具有175
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")
我的猜测是,线索可能是以下事实:连接两个数据框时我正在使用的列具有不同的级别(因此将其转换为字符串),但是我很ham愧地承认我仍然不了解我在这里有错误.我假设我的数据框有问题,尽管我不得不承认即使使用较小的数据框也无法解决问题:
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)
推荐答案
已还是您的数据
table(df$iso_a3)
这篇关于如何将空间数据与Dataframe结合在一起,以便可以与Tmap一起显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!