Tmap Error - replacement has [x] rows, data has [y]

十年热恋 提交于 2020-01-11 13:13:07

问题


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

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

Disclaimer: I have already checked other answers like this one or this one as well as this explanation that states that usually this error comes from misspelling objects, but could not find an answer to my problem.

Reproducible code:

library(rgdal)
library(dplyr)
library(tmap)

# Load JSON file with countries.
countries = readOGR(dsn = "https://gist.githubusercontent.com/ccamara/fc26d8bb7e777488b446fbaad1e6ea63/raw/a6f69b6c3b4a75b02858e966b9d36c85982cbd32/countries.geojson")

# Load dataframe.
df = read.csv("https://gist.githubusercontent.com/ccamara/fc26d8bb7e777488b446fbaad1e6ea63/raw/754ea37e4aba1b7ed88eaebd2c75fd4afcc54c51/sample-dataframe.csv")


countries@data = left_join(countries@data, df, by = c("iso_a2" = "country_code"))

qtm(countries, "freq")

回答1:


Your error is in the data - the code works fine.

What you are doing right now is:

1) attempting a 1:1 match

2) realize that your .csv data contains several ids to match

3) a left-join then multiplies the left hand side with all matches on the right hand-side

To avoid this issue you have to aggregate your data one more time like:

library(dplyr)

df_unique = df %>%
    group_by(country_code, country_name) %>%
    summarize(total = sum(total), freq = sum(freq))


#after that you should be fine - as long as just adding up the data is okay.
countries@data = left_join(countries@data, df, by = c("iso_a2" = 
"country_code"))

qtm(countries, "freq")


来源:https://stackoverflow.com/questions/46298066/tmap-error-replacement-has-x-rows-data-has-y

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