Warning in R maps - r

I am trying to map a bunch of countries with the following code.
require(mapdata)
# get the names
cc <- map('world', names = TRUE, plot = FALSE)
take <- unlist(sapply(c("iran", "malaysia", "saudi arabia", "united arab emirates", "kuwait", "bahrain", "indonesia", "qatar", "sudan", "pakistan", "bangladesh", "turkey", "egypt", "united kingdom", "jordan", "brunei", "sri lanka", "oman", "yemen", "lebanon", "kenya"), grep, tolower(cc), value = TRUE))
suppressWarnings(map())
suppressWarnings(map('world', regions=take, fill=TRUE, col='red', add = TRUE))
I get what I want, however, the Pdf version has the following warning printed on page
#### # maps v3.1: updated 'world': all lakes moved to separate new ### # 'lakes' database. Type '?world' or 'news(package="maps")'. #
I use suppressWarnings, but the warning is still printed. How can I hide this when I knit the document with knitr?

Related

R mutate() and case_when() does not add values to the new field

I created a new field where I intend to populate some data(continents) from some vectors, based on data of an existing column(country). There are several datasets involved in the analysis and the code worked perfectly on only the last table, but the other tables which are as much of importance failed to fill in continents to the required column.
meats_long <- meats_long %>%
add_column(Territory = NA)
Africa <- c("Cote d'Ivoire", "Madagascar", "South Africa", "Ghana", "Morocco", "Ethiopia", "Kenya","Egypt")
NorthAmerica <- c("Mexico","Panama","Jamaica", "Dominican Republic","Nicaragua","Honduras","Costa Rica","Guatemala","Canada","El Salvador")
Europe <- c("Iceland","Belgium-Luxembourg","Ukraine","Latvia","Sweden","Greece","Portugal","Russia","Poland","Denmark","Norway","Switzerland","Austria","Germany","Netherlands","Spain","France","Italy","Ireland","United Kingdom")
Asia <- c("Taiwan","Turkey", "Pakistan","Japan","China","Vietnam", "Hong Kong","Thailand","India","Indonesia","Philippines","Korea, South","Malaysia","Israel","Sri Lanka","Pakistan")
Oceania <- c("Australia","Other Pacific Islands, NEC")
SouthAmerica <- c("Uruguay","Bolivia","Colombia","Argentina","Ecuador","Peru","New Zealand", "Brazil","Chile")
Others <- c("Rest of world")
meats_long <- meats_long %>%
mutate(Territory = case_when(Source %in% Africa ~ "Africa",
Source %in% NorthAmerica ~ "North America",
Source %in% Europe ~ "Europe",
Source %in% Asia ~ "Asia",
Source %in% Oceania ~ "Oceania",
Source %in% SouthAmerica ~ "South America",
Source %in% Others ~ "Rest of world"))

Shiny - filter a variable with %in% and a vector defined by an input

Is it possible in Shiny to filter one variable of a dataframe based on an externally defined vector, which can be selected as an input?
The minimum reproducible example demonstrates the problem. Running the code, you will see that the output table is empty.
When I replace the input$region value with one of the vectors that can be selected, it works. So I guess that the problem is in how the radioButtons input or selectInput returns the vector.
I have studied the documentation for selectInput on cran which suggests that it is possible to group: "" #param choices List of values to select from. If elements of the list are
named, then that name --- rather than the value --- is displayed to the
user. It's also possible to group related inputs by providing a named list
whose elements are (either named or unnamed) lists, vectors, or factors. In
this case, the outermost names will be used as the group labels (leveraging
the <optgroup> HTML tag) for the elements in the respective sublist. See
the example section for a small demo of this feature.
The following stackoverflow QAs Dependent filter in shiny inputs and Filtering from selected input in R shiny address some issues, but they do not answer the same problem, as they filter the variable based on values extracted from the unique values of the variable itself.
Below a minimum reproducible example.
#library(dplyr)
#library(shiny)
#Sample data
Country <- c("Finland", "Estonia", "Kuwait", "Germany", "Italy", "Belgium", "Ukraine", "Belgium", "Italy", "Italy", "Belarus", "Turkey", "Italy", "Switzerland", "Turkey", "France", "Turkey", "Denmark", "Latvia", "United Arab Emirates", "Spain")
Organisation <- c("FIN", "LOT", "KAC", "EZY", "RYR", "BEL", "MSI", "RYR", "AZA", "RYR", "BRU", "THY", "AZA", "EZS", "THY", "TVF", "PGT", "SAS", "BTI", "UAE", "RYR")
Operations <- c(10, 2, 1, 50, 32, 18, 12, 63, 41, 1, 13, 15, 28, 33, 14, 8, 11, 52, 27, 2, 19)
test_data <- data.frame(Country, Organisation, Operations)
Europe <- c("Finland", "Estonia", "Germany", "Italy", "Belgium", "Belarus", "Turkey", "Switzerland", "Denmark", "Latvia", "Spain")
EU <- c("Finland", "Estonia", "Germany", "Italy", "Belgium", "Denmark", "Latvia", "Spain")
#Shiny
# UI
ui <- fluidPage(
radioButtons("region", "Select Departure Region",
choices = c("Europe", "EU")),
# selectInput("region", "Select a Departure Region",
# list('Europe' = list("Finland", "Estonia", "Germany", "Italy", "Belgium", "Belarus", "Turkey", "Switzerland", "Denmark", "Latvia", "Spain"),
# 'EU'= list("Finland", "Estonia", "Germany", "Italy", "Belgium", "Denmark", "Latvia", "Spain"))
# ), #Is the problem that the vector is not correctly defined when selected? However, even creating a list does not result in the same output, as a normal dplyr %in% filter
tableOutput("Market_Table")
)
server <- function(input, output) {
#Does not work; though works if I use the Vector in place of the input variable
# filtered_data <- reactive({
# test_data[test_data$Country %in% input$region, ] .
# })
filtered_data <- reactive({
test_data %>% filter(Country %in% input$region) #Should some sort of reference to .env be used? .env$input$region however does not work.
})
#suggested in Mastering Shiny chapter 12.2.1 but also does not correctly filter - nothing appears in the table
# filtered_data <- reactive({
# test_data[test_data$Country %in% input$region, ]
# })
output$Market_Table <- renderTable({filtered_data()})
}
# Run the application
shinyApp(ui = ui, server = server)
Calling input$region is returning the selected object's name as a string. Use the get() function to return the values of a named object:
...
server <- function(input, output) {
filtered_data <- reactive({
test_data %>% filter(Country %in% get(input$region))
})
...

Create a map using Gapminder package data in R?

I am trying to create a map using the Gapminder package in R.
I have a basic map working, using the choroplethr package. But creating the map requires some data manipulation and the map and legend aren't particularly pretty looking. For example:
library(gapminder)
library(dplyr)
library(choroplethr)
# load data
data(gapminder, package = "gapminder")
# set up data for plot
plotdata <- gapminder %>%
filter(year == 2007) %>%
rename(
region = country,
value = lifeExp
) %>%
mutate(region = tolower(region)) %>%
mutate(region = recode(region,
"united states" = "united states of america",
"congo, dem. rep." = "democratic republic of the congo",
"congo, rep." = "republic of congo",
"korea, dem. rep." = "south korea",
"korea. rep." = "north korea",
"tanzania" = "united republic of tanzania",
"serbia" = "republic of serbia",
"slovak republic" = "slovakia",
"yemen, rep." = "yemen"
))
# make plot
country_choropleth(plotdata, legend = "life expectancy")
I was wondering if there are any other packages that could allow me to plot a map of the life expectancy using the Gapminder data from the Gapminder package?
Preferably, I would like to keep the data manipulation as minimal as possible (I need to demonstrate it to teenagers)... although I realise this may not be possible. Is there an easier way to plot this data on a map?
Any suggestions would be greatly appreciated.

Interactive Europe map R Shiny with ggmap

For a group project, I wanted to create a interactive Europe map, based on this data set: https://ourworldindata.org/causes-of-death.
I have manage to create this map, which will display the number of deaths caused by drowning in 2019 in Europe. But I would like to create an interactive map where the user could enter the cause of deaths for example HIV or Fire, so that the map could display it. I have tried to use an input but it doesn't work and shows me this error message : "Error in : Discrete value supplied to continuous scale". I know that the cause of this issue is the fact that the parameter size is a int but the input a char.
Unfortunalty I don't know how to correct this issue :(
Can anyone help me with it?
Have a nice day,
AM.
library("maptools")
library(rgdal)
library(maps)
library("jsonlite")
library(RColorBrewer)
library(ggmap)
rowdb <- read.csv("annual-number-of-deaths-by-cause.csv", sep = ';')
rowdb <- select(rowdb, -X.1, -X)
europe <- c(left = -12, bottom = 35, right = 30, top = 63)
map_E <- get_stamenmap(europe, zoom = 5,"toner-lite")
ggmap(map_E)
#On va cr?er une variable contenant les noms des pays du continent puis pour une date donn?e
#qu'on pourra aussi demander ? l'utilisateur de s?lectionner on affichera la carte du
#continent et la cause choisies
Europe_E <- c("Albania", "Andorra", "Armenia", "Austria","Azerbaijan","Belarus",
"Belgium", "Bosnia and Herzegovina", "Bulgaria", "Croatia","Cyprus",
"Czechia", "Denmark", "Estonia", "Finland", "France", "Georgia",
"Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy",
"Kazakhstan","Latvia", "Lithuania", "Luxembourg", "Malta", "Moldova", "Monaco",
"Montenegro", "Netherlands","North Macedonia", "Norway", "Poland", "Portugal",
"Romania", "Russia", "San Marino","Serbia", "Slovakia", "Slovenia", "Spain",
"Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom")
#Fonction pour avoir la latitude et longitude des pays
if (!(require(jsonlite))) install.packages("jsonlite")
mygeocode <- function(adresses){
# adresses est un vecteur contenant toutes les adresses sous forme de chaine de caracteres
nominatim_osm <- function(address = NULL){
## details: http://wiki.openstreetmap.org/wiki/Nominatim
## fonction nominatim_osm propos?e par D.Kisler
if(suppressWarnings(is.null(address))) return(data.frame())
tryCatch(
d <- jsonlite::fromJSON(
gsub('\\#addr\\#', gsub('\\s+', '\\%20', address),
'http://nominatim.openstreetmap.org/search/#addr#?format=json&addressdetails=0&limit=1')
), error = function(c) return(data.frame())
)
if(length(d) == 0) return(data.frame())
return(c(as.numeric(d$lon), as.numeric(d$lat)))
}
tableau <- t(sapply(adresses,nominatim_osm))
colnames(tableau) <- c("lon","lat")
return(tableau)
}
latlon_E <- mygeocode(Europe_E)
#is(lalo)
dat_E <- as.data.frame(latlon_E)
DAT_E <- rowdb
DAT_E$Year <- year(as.Date(DAT_E$Year, format = "%Y"))
DAT_E <- DAT_E[
as.character(DAT_E$Year) %in% c("2019"), ]
DAT_E <- DAT_E[
DAT_E$Entity %in% Europe_E, ]
ggmap(map_E, extent = "device") +
geom_point(data = DAT_E, aes(x = dat_E$lon , y =dat_E$lat, color = Europe_E, size = Drowning), alpha = 0.5) +
geom_text(data = DAT_E, aes(x = dat_E$lon, y = dat_E$lat, label = Drowning), color = "black", size = 3.7) +
scale_size_continuous(range = c(6, 12)) + theme(legend.position = "none")+
facet_wrap(~ Year)

Display SpatialPolygonsDataFrame on leaflet map with R

I would like to display the polygon of Canada on a leaflet map.
# create map
library(leaflet)
m = leaflet() %>% addTiles()
m
I was able to find the polygon for Canada: http://www.gadm.org/country.
I chose the SpatialPolygonsDataFrame format for R, but there are other formats available (such as Shapefile)
# load object in R
load("country_polygons/CAN_adm0.RData")
pol_can <- gadm
How can I display the shape on the map? I assume I have to leverage the sp package but I could not figure out how to do so.
Many thanks in advance for your help!
You can pass a SpatialPolygons* object to the addPolygons function as per Section 2.2 of the docs here.
For example (note that the following includes a ~11.4 MB download):
library(sp)
download.file('http://biogeo.ucdavis.edu/data/gadm2/R/CAN_adm0.RData', f <- tempfile())
load(f)
leaflet() %>% addTiles() %>% addPolygons(data=gadm, weight=2)
Note that GADM data can also be downloaded with the getData function in the raster package:
library(raster)
can <- getData('GADM', country='VAT', level=0)
EDIT
In response to the comments, I really like the lightweight polygon datasets that Natural Earth provides. Here's an example where I download the 1:50,000,000 countries shapefile (Admin 0) from Natural Earth, subset it to the current members of the Commonwealth of Nations, and plot those. The zipped shapefile is under 1 MB.
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')
commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh",
"Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
"Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
"Kiribati", "Lesotho", "Malawi", "Malaysia", "Maldives", "Malta", "Mauritius",
"Mozambique", "Namibia", "Nauru", "New Zealand", "Nigeria", "Pakistan", "Papua
New Guinea", "Rwanda", "St. Kitts and Nevis", "Saint Lucia", "St. Vin. and
Gren.", "Samoa", "Seychelles", "Sierra Leone", "Singapore", "Solomon Is.",
"South Africa", "Sri Lanka", "Swaziland", "Tanzania", "Tonga", "Trinidad and
Tobago", "Tuvalu", "Uganda", "United Kingdom", "Vanuatu", "Zamibia")
leaflet() %>% addTiles() %>%
addPolygons(data=subset(world, name %in% commonwealth), weight=2)

Resources