Automatically load map in R from script on startup error - r

I've been trying to get this working without any luck (I'm new to R so don't really know how to do much and have been following examples). Basically I have an R script created that will automatically load a map when run, saved as .R file:
library(maps)
library(maptools)
library(mapdata)
map('worldHires',
c('UK', 'Ireland', 'Isle of Man','Isle of Wight'),
xlim=c(-11,3), ylim=c(49,60.9))
I want this to happen automatically when I open the RGui without having to go to load script, and then select run all. I've read about editing the Rprofile.site file which I've done and I've added an entry to it:
.First <- function(){
library(maps)
library(maptools)
library(mapdata)
map('worldHires',
c('UK', 'Ireland', 'Isle of Man','Isle of Wight'),
xlim=c(-11,3), ylim=c(49,60.9))
}
However, when I start R, I think it loads the libraries but then it says:
Error in maptype(database) : could not find function "data"
and no map is produced. However it works perfectly fine when I load the script manually and then press run all.
Am I doing something wrong here? Does the .First function only load packages? What would make it work? I've also tried just using source(script location) in the first function and that gives the same error.

The problem you are getting is that .First scripts can only use functions in the base package, unless the packages have been explicitly loaded. So in your case, you need to load
utils for the data function.
graphics for the par function.
Putting this together gives:
.First <- function() {
library(utils); library(graphics)
library(maps)
library(maptools)
library(mapdata)
map('worldHires',
c('UK', 'Ireland', 'Isle of Man','Isle of Wight'),
xlim=c(-11,3), ylim=c(49,60.9))
}

Related

Loading libraries for use in an specific environment in R

I have written some functions to facilitate repeated tasks among my R projects. I am trying to use an environment to load them easily but also prevent them from appearing when I use ls() or delete them with rm(list=ls()).
As a dummy example I have an environment loader function in a file that I can just source from my current project and an additional file for each specialized environment I want to have.
currentProject.R
environments/env_loader.R
environments/colors_env.R
env_loader.R
.environmentLoader <- function(env_file, env_name='my_env') {
sys.source(env_file, envir=attach(NULL, name=env_name))
}
path <- dirname(sys.frame(1)$ofile) # this script's path
#
# Automatically load
.environmentLoader(paste(path, 'colors_env.R', sep='/'), env_name='my_colors')
colors_env.R
library(RColorBrewer) # this doesn't work
# Return a list of colors
dummyColors <- function(n) {
require(RColorBrewer) # This doesn't work
return(brewer.pal(n, 'Blues'))
}
CurrentProject.R
source('./environments/env_loader.R')
# Get a list of 5 colors
dummyColors(5)
This works great except when my functions require me to load a library. In my example, I need to load the RColorBrewer library to use the brewer.pal function in colors_env.R, but the way is now I just get an error Error in brewer.pal(n, "Blues") : could not find function "brewer.pal".
I tried just using library(RColorBrewer) or using require inside my dummyColors function or adding stuff like evalq(library("RColorBrewer"), envir=parent.env(environment())) to the colors_env.R file but it doesn't work. Any suggestions?
If you are using similar functions across projects, I would recommend creating an R package. It's essentially what you're doing in many ways, but you don't have reinvent a lot of the loading mechanisms, etc. Hadley Wickham's book R Packages is very good for this topic. It doesn't need to be a completely fully built out, CRAN ready sort of thing. You can just create a personal package with misc. functions you frequently use.
That being said, the solution for your specific question would be to explicitly use the namespace to call the function.
dummyColors <- function(n) {
require(RColorBrewer) # This doesn't work
return(RColorBrewer::brewer.pal(n, 'Blues'))
}
Create a package and then run it. Use kitten to build the boilerplate, copy your file to it, optionally build it if you want a .tar.gz file or omit that step if you don't need it and finally install it. Then test it out. We have assumed colors_env.R, shown in the question, is in current directory.
(Note that require should always be within an if so that if it does not load then the error is caught. If not within an if use library which will guarantee an error message in that case.)
# create package
library(devtools)
library(pkgKitten)
kitten("colors")
file.copy("colors_env.R", "./colors/R")
build("colors") # optional = will create colors_1.0.tar.gz
install("colors")
# test
library(colors)
dummyColors(5)
## Loading required package: RColorBrewer
## [1] "#EFF3FF" "#BDD7E7" "#6BAED6" "#3182BD" "#08519C"

R Colab library error message: 'Error in library(package) : there is no package called ‘package’'

I'm trying to find a package that will let me add north arrows and scale bars to map plots in R.
I can see ggspatial and ggsn can both do this. I'm using colab and have been able to install and access all other packges and create maps succesfully. I can install both the gssn and geospatial package fine. But when I run 'library(package)' I get the same error whenever I try to import either package.
My code:
%load_ext rpy2.ipython
%%R
install.packages(c("ggplot2", "devtools", "dplyr", "stringr"))
install.packages(c("maps", "mapdata", "ggmap", "sf", "gssn")) # or "geospatial" in place of "gssn"
%%R
library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)
library(gssn) # or deospatial in place of geospatial
All other packges install fine, but I get this error after the 'library(ggspatial)' or 'library(gssn)' lines, e.g with geospatial:
RInterpreterError: Failed to parse and evaluate line 'library(ggplot2)\nlibrary(ggmap)\nlibrary(maps)\nlibrary(mapdata)\nlibrary(ggspatial)\n'.
R error message: 'Error in library(ggspatial) : there is no package called ‘ggspatial’'
How do I fix this?

Cannot run map_data("state")

I am trying to work on a US map in R. I have done it a lot of times but this time it gives me this error when I try to load:
us<- map_data("state")
Error in .C(C_map_type, as.character(mapbase), integer(1)) :
Incorrect number of arguments (2), expecting 0 for ''
I have ggmap and ggplot2 libraries loaded. Where am I going wrong?
You need the 'maps' package along with ggmap.
library(maps)
library(ggmap)
us<- map_data("state")
This should work
It looks like there are bugs in tidyverse which interferes with ggplot2 maps functionality. See this related question.
This works in a clean, freshly-restarted R session:
us <- ggplot2::map_data("state")
However, this does not:
library(tidyverse)
us2 = ggplot2::map_data("state")

R Leaflet: lines missing when plotting polylines

I have a pretty simple spatial object composed of a bunch of lines. I can plot it in different ways with no problems: QGIS, mapshaper.org. Even the standard R plot() function:
But when I plot it with leaflet(), some segments mysteriously disappear, leaving disconnected lines behind:
A reproducible example follows. NOTE: I use a GeoJSON source file for simplicity here. I have also tried saving the lines as an ESRI shapefile, with the same effect: The data is plotted OK with QGIS, or plot(), etc but not with leaflet().
library(leaflet)
library(rgdal)
download.file("https://www.dropbox.com/s/nij2oa2rp7ijaaj/commuter_rail.geojson?dl=1",
method = "auto", mode = "wb", destfile = "commuter_rail.json")
commuterLines <- readOGR("commuter_rail.json",
"OGRGeoJSON")
# Straight R Plot - Looks good
plot(commuterLines)
# Plot using leaflet - Some lines are missing!
leaflet() %>% addPolylines(data = commuterLines)
UPDATE:
Here's the reproducible example running as a shiny app, hosted at shinyapps.io, and showing the weird leaflet behavior: https://havb.shinyapps.io/leaflet_example/
UPDATE: the problem seems to be a bug in an older version of the leaflet package available from CRAN. Installing the latest development version from Github resolves the issue.
I don't have enough rep to comment, but I tried your code and it worked for me:
Perhaps it has something to do with your local configuration? Have you tried reinstalling the leaflet package?

"Error opening SHP file" when loading from package data

I want to shift some of my most commonly used shapefiles to github. I have a new package in development. It worked when built in RStudio, but when I pull the package from github and run it I get the error "Error in getinfo.shape(filen) : Error opening SHP file". When I look inside the package the shapefiles are in place in the data folder. They're being called by individual functions, e.g.
load_lon = function(){
require(maptools)
lon <<- readShapePoly('data/london_outline_simple.shp', proj4string=CRS('+init=epsg:27700'))
}
Presumably this method means R is wrongly looking for subfolder 'data' in the working directory. But I can't think how else to call them, as data() doesn't support shp. Grateful for advice how to load them in.
In line with #josh-obrien's comment, the answer is to put data files in a subfolder of inst, whereupon they'll be compiled with the code when the package is built. I've put the shapefiles in:
$SOURCEDIR/inst/external/
These are installed via functions such as:
load_lon = function(){
require(maptools)
path = system.file("external/london_outline_simple.shp", package="londonShapefiles")
lon <<- readShapePoly(path, proj4string=CRS('+init=epsg:27700'))
}
Check out the working github package for full working example.

Resources