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

1

0

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")
Editorialize answered 19/9, 2017 at 10:26 Comment(0)
U
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")
Unicellular answered 19/9, 2017 at 11:6 Comment(2)
Thank you very much for the explanation and the answer. It is now working!Editorialize
I'm afraid that, despite I thought I had understood what my problem was (having one variable on the left dataframe that matched several variables on the right one, and hence, I needed to group variables on right dataframe) I am facing the same message again, but I'm pretty sure that the problem is another one. If you were so kind to answer, I posted another question here: #46431061 . sorry if I'm asking too much @UnicellularEditorialize

© 2022 - 2024 — McMap. All rights reserved.