Overlay shapefile and rasterlayer in R? - r

I have a raster layer with climate data from the north of Mexico, part of Canada and the US mainland. I am trying to restrict the climate data to only the zone of the US mainland. To do this I thought it would be easy to import a US mainland map and overlay it with my raster data (of course this is turning out to be a lot more difficult than I thought). So far, using the rgdal library, I have managed to import a shapefile including the USA mainland map with states divisions. Now I want to convert this into a raster layer so that can finally overlay it with my initial climate raster layer. This is the code that I am using:
setwd ("C:/Climate_data/USA map")
ogrInfo(".", "USA_mainland_states")
usa_state = readOGR(dsn=".", layer="USA_mainland_states")
##Convert to Raster
r_usa_state <- raster()
extent(r_usa_state) <- extent(usa_state)
rasterize(usa_state,r_usa_state, fun='last')
overlay (r_usa_state, sms_av, fun='mask')
However, now I get the following error:
Error in .readCells(x, cells, 1) : no data on disk or in memory
sms_av is the climate rasterlayer (103936 elements, 823.3 kb).
Also, when I do:
hasValues(r_usa_state)
I get:
FALSE
What am I doing wrong?? Any advice would be GREATLY appreciated!!!!

Related

How to crop a raster and change its cell size and extent to match template raster?

I have a set of bioclimatic rasters that I'd like to crop and change to match my template raster.
This means changing projection, cellsize (the template raster has a bigger cellsize) extent and NA cells so that each non-NA cell on the template raster has matching cell on the bioclimatic rasters.
I don't want to change any cell values (except for the necessary changes in upscaling cell size).
Can anyone suggest a workflow in R? I looked through the "raster" package but was unable to figure out a workflow of which I was 100% sure
I think what you are after is the resample() function in the raster package. Here is a reproducible example of the workflow to do this task. This first code chunk is mostly to set up the data for reproducibility and to get the specific scenario you are asking about:
##Loading Necessary Packages##
library(raster)
library(tmap)
library(sf)
library(sp)
library(spData)
##Getting Example Datasets##
data("land")
data("us_states")
##Converting the Elevation layer in the "land" dataset to a rasterLayer##
Elev<-raster(xmx=180, xmn=-180, ymx=90, ymn=-90, t(land$elevation), crs=crs("+init=epsg:4326"))
##Looking at the dataset##
tmap_mode("plot")
tm_shape(Elev)+
tm_raster(palette = terrain.colors(10))+
tm_layout(legend.outside = TRUE)
##Getting necessary projections for spatial transformations##
WGS84<-CRS("+init=epsg:4326")#World Geographical System of 1984
ORLAMB<-CRS("+init=epsg:2992")#Oregon Statewide Lambert Projection
##Creating a fake raster for the US state of Oregon##
OR<-as_Spatial(us_states[us_states$NAME=="Oregon",])
OR_sp<-spTransform(OR, CRSobj=WGS84)
OR_lamb<-spTransform(OR, CRSobj=ORLAMB)
EXT<-extent(OR_lamb)
OR_blank<-raster(EXT, resolution=c(3000,3000), crs=ORLAMB)
values(OR_blank)<-runif(369238, 100, 200)
Now we have the specific scenario you are after we have a big world wide elevation data set projected in to WGS84, and a finer resolution fake raster for the US state of Oregon. The below portion is the main part of the workflow you are asking about
OR_ELEV_tmp<-crop(Elev, OR_sp) #Crop the worldwide elevation data to the state of ORegon
ORELEVLAMB<-projectRaster(OR_ELEV_tmp, crs=ORLAMB)#Project into Oregon Statewide Lambert
ELEV_rsmpld<-mask(resample(ORELEVLAMB, OR_blank),OR_lamb)#Resample to the resolution of our fake Oregon raster and mask to the shape of the state
##View the final output
tmap_mode("plot")
tm_shape(ELEV_rsmpld)+
tm_raster(palette = terrain.colors(10))+
tm_layout(legend.outside = TRUE)

Is it possible to create a map of the UK counties with the packages spData/tmap

I have recently used the package spData for plotting the London boroughs but I haven't found anything for plotting the counties in the UK.
Is it possible the the package spData contains only a few countries in it?
Thank you for your help,
Andrea
Could this be what you are looking for? A shp of the counties?
spData isn't a complete set of world spatial data.
You can find a complete set (with good county shapes) in the Natural Earth 10m (high resolution) cultural vectors. Here's how I was able to make a quick map of UK counties, coloured by the length of the county name:
library("tmap")
library("tmaptools")
library("rnaturalearth")
library("rnaturalearthhires")
library("sf")
data("states10")
uk_counties <- states10[which(states10$iso_a2 =="GB"),]
uk_counties = st_as_sf(uk_counties)
qtm(uk_counties, fill="name_len")
Once you have this dataframe called uk_counties, you can join it to your data & quickly make some nice maps.
choropleth of uk counties by length of county name

Extract BC census shapefile

I have downloaded the Canada census level polygon shapefiles strong text (https://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/bound-limit-2011-eng.cfm) and imported into R using readOGR function from rgdal package.
However, I am struggling to extract the shapefiles specifically from British Columbia. I have used some of the previous explanations to extract my US state zip codes with success (Choropleth Maps in R - TIGER Shapefile issue).
I need assistance in extracting the BC shapefiles.
I don't know which Geographic area or water feature you have selected from that website. I have downloaded the Digital Boundary File of Provinces/territories. I have read and subsetted British Columbia shapefile using following command
library(rgdal)
df <- readOGR(dsn = "C:\\Users\\User\\Desktop\\gpr_000a11a_e", layer = "gpr_000a11a_e")
#To see the data head
head(df#data)
#To see a particular column of the shapefile
df#data$PRENAME
#Subsetting British Columbia from the shapefile
BC = subset(df, PRENAME=="British Columbia")
#Plotting it
plot(BC)

I want to rasterise a shape file but it is taking me ages to complete and have not succeeded yet. Can anyone tell me why?

I have a shapefile that I made in qgis of a national park with landcover type. I clipped a large shapefile of Thailand with a smaller shapefile of just the park. This file (DPKY.lc5) is now 10.5 Mb. When I run the code it takes forever and has not been successful. Why is that?
library(raster)
DPKY.lc5 <- shapefile("dpky.lc5.shp")
DPKY.lc5 <- spTransform(DPKY.lc5, CRS('+init=EPSG:4326'))
DPKY.lc5$VALUE<-as.numeric(DPKY.lc5$VALUE)
rr <- raster(DPKY.lc5, res=0.01)
rr1 <- rasterize(DPKY.lc5, rr, field="VALUE")
rr1
I would expect this to work as it is only 10.5Mb but it takes forever. I need this raster to work so I can use data points in another data frame to show the frequency of elephant habitat use in the park. I succeeded with other raster files to get elevation and slope aspect but this time it doesn't like​ it.

Cropping Netcdf rasters in R

I am still working in the same project where I asked this question.
And I am getting by allright, but my processing times are too long, for each NetCDF file I am reading it, getting a stack form several of the time-slices, and then cropping each of those time slices within r, using a code like the one bellow:
library(raster)
library(ncdf4)
library(ncdf4.helpers)
library(rworldxtra)
data("countriesHigh")
The NETCdf files I have are for all of the world, but I am using only South America, for that I use countiresHigh from the rworldxtra package to subset it:
NONA <- countriesHigh[!is.na(countriesHigh#data$GEO3),]
## get shapefile of South America
SA <- NONA[NONA#data$GEO3 == "South America",]
Then using the following code I crop every layer that I need.
##Open conection to the layer
nc <- nc_open("C:/Users/mean_temperature-15000BP-10000BP.nc")
Now I start a loop
for(i in 1:10){
message(paste("reading layer", i))
# Read the stack for year i
r <- stack("C:/Users/mean_temperaturemean_temperature-15000BP-10000BP.nc", varname = age[i])
#Change the extent to the correct one
extent(r) <- c(-180,180,-90,90)
#Crop it to South America
r <- crop(r, SA)
gc()
}
Problem 1: Can I crop the netcdf once before reading stacks to make this process faster?
I have looked here, here and here, and found no answer.
Problem 2: If I can crop it, how do I define the extent given that the NETCDF file contains only positive latitude and positive longitude
as stated in this question, the defined extent of the map is not the most usual, but I am basing my cropping in the extent of a shapefile that has the more typical c(-180,180,-90,90) extent

Resources