I've created the following script to get the coastline of Denmark
# Get Shapefiles for Coastline
shpurl <- "http://download.geofabrik.de/europe/denmark-latest.shp.zip"
tmp <- tempfile(fileext=".zip")
download.file(shpurl, destfile = tmp)
files <- unzip(tmp, exdir=getwd())
# Load & plot shapefile
library(maptools)
shp <- readShapePoly(files[grep(".shp$", shpurl)])
plot(shp)
This should give me the outline of Denmark, however, I keep getting the following error:
Error in plot.window(...) : need finite 'ylim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
Any help or directions is appreciated.
Have a look at your files value:
> length(files)
[1] 41
The files you are downloading have number of shape files for various geographies. For instance the code:
require(rgdal)
shp <- readOGR(dsn = "whereIsavedyourStuff/Stacks", layer = "roads")
will execute properly. But you will need to specify, which of the sourced shape files you want to read.
As a side point, with respect to reading files from the net, I would suggest that you have a look at this code:
# Download an read US state shapefiles
tmp_shps <- tempfile(); tmp_dir <- tempdir()
download.file("http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_state_20m.zip",
tmp_shps)
unzip(tmp_shps, exdir = tmp_dir)
# Libs
require(rgdal)
# Read
us_shps <- readOGR(dsn = tmp_dir, layer = "cb_2014_us_state_20m")
Irrespectively, of what method to read shape files you decide to use you have to specify path and file name. In terms of the provided code in readOGR this is fulfilled by dns and layer options. In your code you used files[grep(".shp$", shpurl)], file names within your 195MB archive, do not corresponds to the URL. You have a few options here:
You can download this files and unpack as you did, list names of all the files that are *.shp, take the file names and pass them in the loop to a list where you would read all combinations (in effect you need a number of files to read each layer)
Better, specify the layer you want to read similarly to the code provided above.
Related
I have a data set (Data_Base) with the number of murders in one specific year for the 32 Mexican states. I download with the help of the gadm_sf_loadCountries the spatial data for this 32 Mexican states.
Now, I want to merge this data frame with the SF object in order to plot it with filled with the murders per state. The code is the following:
#Export spatial data from Mexico
mex.sf = gadm_sf_loadCountries("MEX", level=1, basefile="./")
mex.sf <- mex.sf$sf
#Merge the SF object and the Data frame
mex.sf <- left_join(Data_Base,mex.sf, by = c('State'='shapeName'))
#Run the graph code, I want to fill the map with the murders per state
ggplot(mex.sf)+geom_sf(aes(fill=murders)) +
scale_fill_manual(values=c("#d7301f","#fc8d59","#fdcc8a","#fef0d9"))
However, at the moment I do the graph I got the following error:
Error: stat_sf requires the following missing aesthetics: geometry
Run `rlang::last_error()` to see where the error occurred.
I honestly don´t know why is showing me this error because the geometry rows have been pasted at the moment I "left joined"it.
Does anyone knows why is this error?
TLDR: change the order of your objects in left_join(Data_Base,mex.sf, ...)
Long version: When joining data items to a {sf} spatial object the order of your objects matters.
The class output of a dplyr::*_join() family of functions (inner, left, whatever...) will be determined by the first argument. The presence of geometry column is not sufficient for the resulting object to behave as expected; class matters.
To illustrate my argument consider this piece of code (I don't have your data on hand, so I make do with the North Carolina shapefile that ships with {sf}):
library(sf)
library(dplyr)
shape <- st_read(system.file("shape/nc.shp", package="sf"))
data <- data.frame(CNTY_ID = 1825,
label = "this be county Ashe")
data_first <- inner_join(data, shape, by = "CNTY_ID") # joining shape to data = this will break later on
class(data_first)
# [1] "data.frame"
plot(data_first["label"]) # this will be a mess...
# Error in plot.window(...) : need finite 'ylim' values
# In addition: Warning messages:
# 1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
# 2: In min(x) : no non-missing arguments to min; returning Inf
# 3: In max(x) : no non-missing arguments to max; returning -Inf
shape_first <- inner_join(shape, data, by = "CNTY_ID") # joining data to shape = this is the way to go!
class(shape_first)
# [1] "sf" "data.frame"
plot(shape_first["label"]) # works like a charm...
I've loaded multiple packages / tried numerous methods to read a .shp. None of the methods work and I'm unable to decipher google related suggestions. Running the code in R, the system freezes and the same code in RStudio.cloud only returns various error messages. A list of the packages and code are below. Ultimately, I'm trying to create maps, join with another file and produce a table of the results. Any suggestions would be appreciated.
library(rgeos)
library(sp)
library(rgdal)
library(maptools)
library(sf)
require(sf)
area <- read_sf(dsn = ".", layer = "2020ATLclip")
require(rgdal)
shape <- readOGR(dsn= ".", layer = "2020ATLclip.shp")
shape <- readOGR(dsn= ".", layer = "tl_2021_13_concity.shp")
library(raster)
l = readShapePoly("2020ATLclip.shp")
l = readShapePoly("tl_2021_13_concity.shp")
atl.poly <- readOGR("./data", layer = "tl_2021-13_concity.shp")
Cannot open layer 2020ATLclip
Error in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
Opening layer failed.
In addition: Warning messages:
1: Unable to open /cloud/project/2020ATLclip.shx or /cloud/project/2020ATLclip.SHX. Set SHAPE_RESTORE_SHX config option to YES to restore or create it. (GDAL error 4)
2: Failed to open file /cloud/project/2020ATLclip.shp. It may be corrupt or read-only file accessed in update mode. (GDAL error 4)
>
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open layer
l = readShapePoly("2020ATLclip.shp")
Error in getinfo.shape(filen) : Error opening SHP file
In addition: Warning message:
readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
> l = readShapePoly("tl_2021_13_concity.shp")
Error in getinfo.shape(filen) : Error opening SHP file
In addition: Warning message:
readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
For both readOGR (from the rgdal package) and st_read (from the newer sf package), when importing a shapefile the dsn= parameter must point to the shp file - with extension *.shp. The layer= parameter is unnecessary with shapefiles. And you must also have the other components of the shapefile format in the same directory: the *.shx, *.dbf, and *.prj. Assuming you have these files in the current working directory, then...
If you insist on using the rgdal library:
library(rgdal)
shape <- readOGR(dsn= "2020ATLclip.shp")
# returns an object of class Spatial*DataFrame from sp
Preferably you should switch to sf, then
library(sf)
shape <- st_read(dsn = "2020ATLclip.shp")
# returns an object of class sf
I have netcdf files of daily temperature and precipitation data
How is it possible to Change projection of a netcdf?
I have tried to doing this using raster function to read the files
and reproject them with projectraster?
Code_used
a <-raster(file.nc)
cr1<-"+proj=longlat +datum=NAD83 +no_defs+ellps=GRS80 +towgs84=0,0,0"
projectRaster(a, cr1,res = 0.04166667)
ERROR_
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘res’ for signature ‘"character"’
In addition: Warning message:
In min(dim(to)[1:2]) : no non-missing arguments to min; returning Inf
The help for projectRaster gives this usage:
Usage:
projectRaster(from, to, res, crs, method="bilinear",
alignOnly=FALSE, over=FALSE, filename="", ...)
if you call it with two unnamed arguments, they get matched to from and to, and to is:
to: Raster* object with the parameters to which 'from' should be
projected
if instead you name the second argument, this should work:
a_project = projectRaster(a, crs = cr1, res = 0.04166667)
because now the second argument is matched as the crs argument.
BUT if you just want to transform a gdal-compatible data set then you can use gdaltransform, either from the command line or via the function with the same name from the gdalUtils package.
I'm having a lot of difficulty creating a prediction grid (for the new_data argument) to use with the autoKrige function in the automap package.
I've already tried following the steps in this post (How to subset SpatialGrid using SpatialPolygon) but get the following error :
Error in x#coords[i, , drop = FALSE] :
(subscript) logical subscript too long
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
My (limited) understanding is the error relates to there being no non-missing arguments because it is an empty grid. This is fine - all I want is an empty grid constrained by a polygon from a shapefile.
Here is the code I'm working with:
shp <- shapefile("C://path/path/Tobay_Box2.shp")
shp <- spTransform (shp,"+proj=utm +ellps=WGS84 +datum=WGS84")
grid <- GridTopology(cellcentre.offset=c(731888.0,7457552.0),cellsize=c(2,2),cells.dim=c(122,106))
grid <- SpatialPixelsDataFrame(grid,
data=data.frame(id=1:prod(122,106)),
proj4string=CRS("+proj=utm +ellps=WGS84 + datum=WGS84"))
plot(grid)
[see dropbox folder 'Grid.png']
bound <- shp#polygons
bound <- SpatialPolygons(bound, proj4string=CRS("+proj=utm +ellps=WGS84 +datum=WGS84"))
plot(bound)
[see dropbox folder 'Boundary plot.png']
clip_grid <- grid[!is.na(over(grid, bound)),]
No errors or warnings up to this point. But then...
plot(clip_grid)
Error in x#coords[i, , drop = FALSE] :
(subscript) logical subscript too long
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
or attempting to pass the object clip_grid through autokrige for the new_data argument:
PerInkrg <- autoKrige (PerArIn~1, hs1, clip_grid)
Error in predict.gstat(g, newdata = newdata, block = block, nsim = nsim, :
value not allowed for: %s %s newdata empty or only NA's
I've had no issues using the non-clipped grid (object = grid).
In a nutshell, I require this [see dropbox folder 'Autokrig plot'] but with the interpolated surfaced constrained (clipped) to the boundary extent of 'Torbay_Box2.shp'
P.S. I attempted to insert images of my plots and links to other posts I've used before asking for help here and a link to my data but as a new user I don't have enough reputation to do this - sorry!
Data and plots can be found on Dropbox.com/sh/yqg20z1ibl3h4aa/AACJnHoEuP-S5fTvAXxsnY1za?dl=0
I've now managed to produce an autoKrige [plot] which is masked to the extent of the Torbay_Box2 boundary. However, I never achieved this in the 'conventional' way by creating a prediction grid like meuse.grid. The result is the same so for now I'm happy but I would still like to do it the conventional way eventually.
Here's how I cheated it:
# Load sample box extent
bx.data <- readOGR (".", "Tobay_Box2")
bx <- spTransform(bx.data,"+proj=utm +ellps=WGS84 +datum=WGS84") #transformsto UTM projection
str(bx)
# Set the boundary extent with that of sample box extent
hs1#bbox <- bx#bbox
#create an empty grid
grd <- as.data.frame(spsample(hs1, "regular", n=50000))
names(grd) <- c("X", "Y")
coordinates(grd) <- c("X", "Y")
gridded(grd) <- TRUE # Create SpatialPixel object
fullgrid(grd) <- TRUE # Create SpatialGrid object
plot(hs1)
plot(grd, pch = ".", add = T)
proj4string(grd) <- proj4string(hs1)
I then performed an IDW interpolation using the empty grid as the newdata, converted the output to raster, clipped this to the Torbay_Box2 boundary and then converted this to a SpatialPixelDataFrame which I passed through as the new_data argument for autoKrige:
# For PerArIn (% area inhabited)
#interpolate the grid cells using all points and a power value of 2
hs1.idw <- gstat::idw(PerArIn ~ 1, hs1, newdata=grd, idp=2.0)
# Convert to raster object then clip to Hollicombe sample box
r <- raster(hs1.idw)
r.m <- mask(r, bx)
#Convert and set as prediction grid for Kriging
grd<- rasterToPoints(r.m, spatial=TRUE)
gridded(grd) <- TRUE
grd <- as (grd, "SpatialPixels")
#en voila!
PerInkrg <- autoKrige (PerArIn~1, hs1,grd)
I need to convert shapefiles into raster format.
I used the function "rasterize" in R package "raster", but the result does not look correct.
tst <- rasterize(shpfile, r, fun="count")
Found 5 region(s) and 5 polygon(s)
There is no gird with occurrence records:
range(tst[],na.rm=TRUE)
[1] Inf -Inf
Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
sum(tst[],na.rm=TRUE)
[1] 0
The R script that I wrote:
# download the GIS shape file
download.file("http://esp.cr.usgs.gov/data/little/abiebrac.zip",
destfile = "abiebrac.zip")
# unzip
unzip("abiebrac.zip")
# Read shapefile into R
library(maptools)
shpfile <- readShapePoly("abiebrac")
extent(shpfile)
# mapping
plot(shpfile)
library(maps)
map("world",xlim=c(-180,-50),ylim=c(7,83),add=FALSE)
plot(shpfile,add=TRUE,lwd=10)
# rasterize
library(raster)
GridSize <- 0.5 # degree
r <- raster(ncol= round(abs(-180-(-50))/GridSize),
nrow=round(abs(83-7)/GridSize))
extent(r) <- extent(c(-180, -50, 7, 83))
tst <- rasterize(shpfile, r, fun="count")
# summary
sum(tst[],na.rm=TRUE)
range(tst[],na.rm=TRUE)
# mapping
plot(tst,col="red",main="abiebrac")
map("world",xlim=c(-180,-50),ylim=c(7,83),add=TRUE)
I am not sure why you are using "count" in the fun argument but in this case, because there is no overlap, it is producing NA results. You also need to define an attribute field in the spatialPolygonDataFrame object to assign values to your raster. You can also pull the extent directly from the sp object.
This code seems to yield what you want.
require(raster)
require(rgdal)
require(sp)
setwd("D:/TMP")
shpfile <- readOGR(getwd(), "abiebrac")
r <- raster(extent(shpfile))
res(r)=0.05
r <- rasterize(shpfile, field="ABIEBRAC_", r)
plot(r)
plot(shpfile,lwd=10,add=TRUE)