Finding the boundary points in a raster data file - r

So, I have with me the center point and the zoom level.
I have to plot some points on the map.
The map is stored in a raster data file, and is displayed on the R's widget.
The issue is that when a point is received, I need to check whether it falls inside the data of this raster file or not.
If the point is in the raster file, then I can safely plot it.
If not, then I need to load another raster file which contains that point, and then plot the point.
The raster package of R has a function named as.data.frame which loads the raster data into the data frame.
Is it possible, then, to figure out which points (lats and lons) are at the four corners?
Am I on the right track?

If your data is of RasterLayer class then extent will give you the extent of the raster
and xmin, 'min, ymax and xmax to access the various slots.
eg
# create a dummy raster
r1 <- raster(nrows=108, ncols=21, xmn=0, xmx=10)
r1[] <-1
extent(r1)
## class : Extent
## xmin : 0
## xmax : 10
## ymin : -90
## ymax : 90
You can access the various slots using
xmin(r1)
## [1] 0
xmax(r1)
##[1] 10
ymin(r1)
## [1] -90
ymax(r1)
## [1] 90
If your data is a SpatialGridDataFrame then bbox will return the bounding box
.grid <- as(r1,'SpatialGridDataFrame')
bbox(.grid)
## min max
## s1 0 10
## 2 -90 90
Does my xy coordinate lie within the raster boundary
you can use cellFromXY to find the cell id, and it will return NA if it is outside the extext
eg
# some data
.points <- rbind(c(1,1),c(-4,1))
# the first point lies within the raster, the second not
# cell from XY will tell you this.
cellFromXY(r1,.points)
## [1] 1116 NA
EDIT for ggmap
if you have a map acquired by get_map, it is a ggmap object, and will not work with the package raster without some help from you .
you can obtain the bounding box as the bb attribute.
hdf <- get_map()
attr(hdf,'bb')
## ll.lat ll.lon ur.lat ur.lon
## 1 29.38048 -95.80204 30.14344 -94.92313
A helper function that will create a RasterStack from a ggmap object
ggmap_rasterlayer <- function(map){
map_bbox <- attr(map, 'bb')
.extent <- extent(as.numeric(map_bbox[c(2,4,1,3)]))
my_map <- raster(.extent, nrow= nrow(map), ncol = ncol(map))
rgb_cols <- setNames(as.data.frame(t(col2rgb(map))), c('red','green','blue'))
red <- my_map
values(red) <- rgb_cols[['red']]
green <- my_map
values(green) <- rgb_cols[['green']]
blue <- my_map
values(blue) <- rgb_cols[['blue']]
stack(red,green,blue)
}
my_map <- ggmap_rasterlayer(hdf)

Related

How to make an equal area grid in r using the terra package

I want to make an equal area grid (400 square miles per grid cell) over Wisconsin. I am doing this using the code from this link: Creating an equal distance spatial grid in R.
But, this code isn't very flexible, and I also need the grid to be more than just polygons. I need it to be a shapefile. I like the Terra package, but am unable to figure out how to do this in the terra package. The WI shapefile can be downloaded from https://data-wi-dnr.opendata.arcgis.com/datasets/wi-dnr::wisconsin-state-boundary-24k/explore.
My code looks like this:
library(sf)
library(terra)
library(tidyverse)
wi_shape <- vect('C:\\Users\\ruben\\Downloads\\Wisconsin_State_Boundary_24K\\Wisconsin_State_Boundary_24K.shp')
plot(wi_shape)
wi_grid <- st_make_grid(wi_shape, square = T, cellsize = c(20 * 1609.344, 20 * 1609.344))
plot(wi_grid, add = T)
How do I define a grid that is centered on a lat/lon point, where the output is a shapefile that contains attributes for each grid cell? I'm not sure why this is so confusing to me. Thank you.
If your goal is to make a raster based on the extent of another spatial dataset (polygons in this case) you can do
library(terra)
wi <- vect('Wisconsin_State_Boundary_24K.shp')
r <- rast(wi, res=(20 * 1609.344))
You can turn these into polygons and write them to a file with
v <- as.polygons(r)
writeVector(v, "test.shp")
To define a lon/lat center for the grid, you could do the following.
Coordinates of an example lon/lat point projected to the crs of your polygons (Wisconsin Transverse Mercator).
center <- cbind(-90, 45) |> vect(crs="+proj=longlat")
cprj <- crds(project(center, wi))
res <- 20 * 1609.344
Create a single cells around that point and expand the raster:
e <- rep(cprj, each=2) + c(-res, res) / 2
x <- rast(ext(e), crs=crs(wi), ncol=1, nrow=1)
x <- extend(x, wi, snap="out")
The result
plot(as.polygons(x), border="blue")
lines(wi, col="red")
points(cprj, pch="x", cex=2)
I should also mention that you are not using an equal-area coordinate reference system. You can see the variation in cell sizes with
a <- cellSize(x)
But it is very small (less than 1%) relative to the average cell size
diff(minmax(a))
# area
#max 1690441
global(a, mean)
# mean
#area 1036257046
Let's try to tidy this a little bit.
[...] and I also need the grid to be more than just polygons. I need it to be a shapefile.
It's exactly the other way around from my point of view. Once you obtained a proper representation of a polygon, you can export it in whatever format you like (which is supported), e.g. an ESRI Shapefile.
I like the Terra package, but am unable to figure out how to do this in the terra package.
Maybe you did not notice, but actually you are not really using {terra} to create your grid, but {sf} (with SpatVector input from terra, which is accepted here).
library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(terra)
#> terra 1.6.33
wi_shape <- vect('Wisconsin_State_Boundary_24K.shp')
class(wi_shape)
#> [1] "SpatVector"
#> attr(,"package")
#> [1] "terra"
wi_grid <- st_make_grid(wi_shape, square = T, cellsize = c(20 * 1609.344, 20 * 1609.344))
class(wi_grid)
#> [1] "sfc_POLYGON" "sfc"
It's a minor adjustment, but basically, you can cut this dependency here for now. Also - although I'm not sure is this is the type of flexibility you are looking for - I found it very pleasing to work with {units} recently if you are about to do some conversion stuff like square miles in meters. In the end, once your code is running properly, you can substitute your hardcoded values by variables step by step and wrap a function out of this. This should not be a big deal in the end.
In order to shift your grid to be centered on a specific lat/lon point, you can leverage the offset attribute of st_make_grid(). However, since this only shifts the grid based on the original extent, you might lose coverage with this approach:
library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
wi_shape <- read_sf("Wisconsin_State_Boundary_24K.shp")
# area of 400 square miles
A <- units::as_units(400, "mi^2")
# boundary length in square meters to fit the metric projection
b <- sqrt(A)
units(b) <- "m"
# let's assume you wanted your grid to be centered on 45.5° N / 89.5° W
p <- c(-89.5, 45.5) |>
st_point() |>
st_sfc(crs = "epsg:4326") |>
st_transform("epsg:3071") |>
st_coordinates()
p
#> X Y
#> 1 559063.9 558617.2
# create an initial grid for centroid determination
wi_grid <- st_make_grid(wi_shape, cellsize = c(b, b), square = TRUE)
# determine the centroid of your grid created
wi_grid_centroid <- wi_grid |>
st_union() |>
st_centroid() |>
st_coordinates()
wi_grid_centroid
#> X Y
#> 1 536240.6 482603.9
# this should be your vector of displacement, expressed as the difference
delta <- wi_grid_centroid - p
delta
#> X Y
#> 1 -22823.31 -76013.3
# `st_make_grid(offset = ...)` requires lower left corner coordinates (x, y) of the grid,
# so you need some extent information which you can acquire via `st_bbox()`
bbox <- st_bbox(wi_grid)
# compute the adjusted lower left corner
llc_new <- c(st_bbox(wi_grid)["xmin"] + delta[1], st_bbox(wi_grid)["ymin"] + delta[2])
# create your grid with an offset
wi_grid_offset <- st_make_grid(wi_shape, cellsize = c(b, b), square = TRUE, offset = llc_new) |>
st_as_sf()
# append attributes
n <- dim(wi_grid_offset)[1]
wi_grid_offset[["id"]] <- paste0("A", 1:n)
wi_grid_offset[["area"]] <- st_area(wi_grid_offset) |> as.numeric()
# inspect
plot(st_geometry(wi_shape))
plot(st_geometry(wi_grid_offset), border = "red", add = TRUE)
If you wanted to export your polygon features ("grid") in shapefile format, simply make use of st_write(wi_grid_sf, "wi_grid_sf.shp").
PS: For this example you need none of the tidyverse stuff, so there is no need to load it.

Plotting points extracted from a dataframe in a Raster layer

I would like to plot points from a data frame into a raster layer that I have. For every point, I would like the value of the cell to be 1 (all the other cell on the initial raster layer have a value of zero).
My dataframe (data) looks like this (first three rows only)
Year<-c(2020, 2019, 2018)
Lat<-c(48.3,48.79,48.4)
Long<-c(-123.62, -123.36, -123.29)
I managed to plot those points with the following code
points = st_as_sf(data, coords = c("Long", "Lat"), crs = 4326)
plot(st_geometry(points), pch=16, col="navy")
And got this graph:
Graph points plotted
I now want to plot those points into a raster layer that I have for the area.
The parameters of my raster layer are as follow:
class : RasterLayer
dimensions : 44, 41, 1804 (nrow, ncol, ncell)
resolution : 0.2916667, 0.2916667 (x, y)
extent : -133.2625, -121.3042, 41.3875, 54.22083 (xmin, xmax, ymin, ymax)
crs : NA
names : Blank_Map
Every cell of this raster as a value of 0, which is what I need. Now, I would like to add the points from my dataframe to this raster layer, using of value 1 for every cell where those data points are. I would also like to save the whole thing as a new raster layer (which would then have 0 and 1 values).
Could anybody help me achieve this?
I have been trying for days, but nothing seems to work
any help is appreciated!
1. Please find below a reprex providing a possible solution using raster and sf libraries.
library(raster)
library(sf)
# Create from scratch the raster with 0 values
raster0 <- raster(nrows = 44, ncols = 41,
xmn = -133.2625, xmx = -121.3042,
ymn = 41.3875, ymx = 54.22083,
vals=0)
# Convert points 'sf' object into 'sp' object
points_sp <- as(points, "Spatial")
# Extract the cells of raster0 matching the points geometry of the 'sp' object
cells_ID <- extract(raster0, points_sp, cellnumbers=TRUE)[,"cells"]
# Copy raster0 (as you want the final result in another raster)
raster01 <- raster0
# Replace 0 values to 1 for cells matching points geometry in the 'raster01'
raster01[cells_ID] <- 1
# Visualization of the final result
plot(raster01)
Created on 2021-12-07 by the reprex package (v2.0.1)
2. Please find below a reprex providing another solution using terra and sf libraries
library(terra)
library(sf)
# Create from scratch the 'SpatRaster' with 0 values
raster0 <- rast(nrows=44, ncols=41,
nlyrs=1,
xmin=-133.2625, xmax=-121.3042,
ymin=41.3875, ymax=54.22083,
vals = 0)
# Convert points 'sf' object into 'SpatVector' object
points <- vect(points)
# Extract the cells of raster0 matching the points geometry of the 'sp' object
cells_ID <- terra::extract(raster0, points, cells = TRUE)
# Copy raster0 (as you want the final result in another raster)
raster01 <- raster0
# Replace 0 values to 1 for cells matching points geometry in the 'raster01'
raster01[cells_ID[,"cell"]] <- 1
# Visualization of the final result
plot(raster01)
Created on 2021-12-07 by the reprex package (v2.0.1)

How can I get the number of pixels with NA value in a raster that is cliped from a large raster by many polygons?

I applied cloud mask to a raster image in R, and want to check how many pixels are masked out. But what I really need are only the images within some polygons (400+ of them), so I only want to get the number of pixels with no value within the polygons.
Here is what I have done:
library(raster)
library(rgdal)
##Read the raster files
tb = raster('D:/HLS/NDVI_Month_2018_TB.tif', band = 6)
##Read the polygon (400 polygons)
crops = readOGR('D:/HLS/shapefile/tb/tb.shp')
##reproject the vector
new_crops = spTransform(crops, crs(tb))
##Clip the raster with polygons
cliped = crop(tb, extent(new_crops))
output = mask(cliped, new_crops)
##Check the NA value
freq(output, value = NA)
However what I got from the freq() function seems to be all the pixels within the area (not only the polygons but the area from crop() function).
The result of freq():
How can I get the NA value within the polygons?
Here is a minimal, self-contained, reproducible example (taken mostly from ?raster::extract)
Example raster and polygons
library(raster)
r <- raster(ncol=90, nrow=45)
values(r) <- 1:ncell(r)
r[seq(1,ncell(r),3)] <- NA
p1 <- rbind(c(-180,-20), c(-140,55), c(0, 0), c(-140,-60), c(-180,-20))
p2 <- rbind(c(10,0), c(140,60), c(160,0), c(140,-55), c(10,0))
pols <- spPolygons(p1, p2)
Solution 1
extract(r, pols, fun=function(i, ...) sum(is.na(i)))
# [,1]
#[1,] 215
#[2,] 178
Solution 2
z <- rasterize(pols, r)
zonal(is.na(r), z, "sum")
# zone sum
#[1,] 1 215
#[2,] 2 178

Draw polygon from raster after occurrence modeling

I want to draw polygons for species occurrence using the same methods BIEN uses, so I can use both my polygons and theirs. They use Maxent to model species occurrence when they have more then occurrence points.
So, this is, for example, a BIEN polygon:
library(BIEN)
Mormolyca_ringens<- BIEN_ranges_load_species(species = "Mormolyca ringens")
#And this is a polygon, yes. A SpatialPolygonsDataFrame.
plot(wrld_simpl, xlim=c(-100,-40), ylim=c(-30,30), axes=TRUE,col="light yellow", bg="light blue")
plot(Mormolyca_ringens, col="green", add=TRUE)
Mormolyca ringens polygon
Ok, then I'm trying to draw my polygons because BIEN lacks some for species I need.
# first, you need to download the Maxent software here: http://biodiversityinformatics.amnh.org/open_source/maxent/
#and paste the "maxent.jar" file in the ’java’ folder of the ’dismo’ package, which is here:
system.file("java", package="dismo")
#You have to do this **before** loading the libraries
#install.packages("rJava")
library(rJava)
#If you get the message that cannot load this library, it's possible that your version of java is not 64bit.
#Go to Oracle and install Java for windows 64bit.
#If library still doesn't load: Look in your computer for the path where the java's jre file is and paste in the code below
Sys.setenv(JAVA_HOME="your\\path\\for\\jre") #mine is "C:\\Program Files\\Java\\jre1.8.0_144", for example
library(rJava)
library(dismo)
library(maptools)
#Giving credits: I wrote the following code based on this tutorial: https://cran.r-project.org/web/packages/dismo/vignettes/sdm.pdf
#Preparing the example data - the map
data(wrld_simpl)
ext = extent(-90, -32, -33, 23)
#Preparing the example data - presence data for Bradypus variegatus
file <- paste(system.file(package="dismo"), "/ex/bradypus.csv", sep="")
bradypus <- read.table(file, header=TRUE, sep=',')
bradypus <- bradypus[,-1] #don't need th first col
#Getting the predictors (the variables)
files <- list.files(path=paste(system.file(package="dismo"),
'/ex', sep=''), pattern='grd', full.names=TRUE )
predictors <- stack(files)
#making a training and a testing set.
group <- kfold(bradypus, 5)
pres_train <- bradypus[group != 1, ]
pres_test <- bradypus[group == 1, ]
#Creating the background
backg <- randomPoints(predictors, n=1000, ext=ext, extf = 1.25)
colnames(backg) = c('lon', 'lat')
group <- kfold(backg, 5)
backg_train <- backg[group != 1, ]
backg_test <- backg[group == 1, ]
# Running maxent
xm <- maxent(predictors, pres_train, factors='biome')
plot(xm)
#A response plot:
response(xm)
# Evaluating and predicting
e <- evaluate(pres_test, backg_test, xm, predictors)
px <- predict(predictors, xm, ext=ext, progress='text', overwrite=TRUE)
#Checking result of the prediction
par(mfrow=c(1,2))
plot(px, main='Maxent, raw values')
plot(wrld_simpl, add=TRUE, border='dark grey')
tr <- threshold(e, 'spec_sens')
plot(px > tr, main='presence/absence')
plot(wrld_simpl, add=TRUE, border='dark grey')
points(pres_train, pch='+')
At this point, I have the following image:
Prediction for example's occurrence
And I'm trying to make a polygon from this raster with this code:
predic_pol<-rasterToPolygons(px )
And also:
px_rec<-reclassify(px, rcl=0.5, include.lowest=FALSE)
px_pol<-rasterToPolygons(px_rec)
But i keep getting a pixels version of my extent
Can you please give me a hint so I can extract a polygon out of this raster, like the BIEN's one? (Also I'm new to modeling and to R... any tips are welcome)
EDIT: this is the px console output:
> px
class : RasterLayer
dimensions : 172, 176, 30272 (nrow, ncol, ncell)
resolution : 0.5, 0.5 (x, y)
extent : -120, -32, -56, 30 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : C:\Users\thai\Documents\ORCHIDACEAE\Ecologicos\w2\predictions\Trigonidiumobtusum_prediction.grd
names : layer
values : 6.705387e-06, 0.9999983 (min, max)
Thank you in advance
Edit 2: Solution
Thanks to #Val I got to this:
#Getting only the values>tr to make the polygon
#"tr" is what gives me the green raster instear of the multicolour one
pol <- rasterToPolygons(px>tr,function(x) x == 1,dissolve=T)
#Ploting
plot(wrld_simpl, xlim=c(-120,-20), ylim=c(-60,10), axes=TRUE,col="light yellow", bg="light blue")
plot(pol, add=T, col="green")
And now I have what I wanted! Thank you!
(The polygon is not the same in the figures only because I used a different data set I had at my environment at the moment I got #Val 's answer)
Bonus question:
Do you know how to smooth the edges so I get a non pixelized polygon?
I don't know BIEN, so I din't really look at this part of your example. I just generalized your problem/question down to the following:
You have a binary raster (with 0 for absence and 1 for presence) and you want to convert all areas with 1 to a polygon.
As for your px raster, it's a bit odd that your values are not 0 and 1 but more basically 0 and basically 1. But if that's a problem, that can be an easy fix.
So I tried to recreate your example with just the area of Brasil:
library(raster)
library(rgeos)
# get Brasil borders
shp <- getData(country = 'BRA',level=0)
#create binary raster
r <- raster(extent(shp),resolution=c(0.5,0.5))
r[] <- NA # values have to be NA for the buffering
# take centroid of Brasil as center of species presence
cent <- gCentroid(shp)
# set to 1
r[cellFromXY(r,cent)] <- 1
# buffer presence
r <- buffer(r,width=1000000)
# set rest 0
r[is.na(r)] <- 0
# mask by borders
r <- mask(r,shp)
This is close enough to your raster I guess:
So now to the conversion to the polygon:
pol <- rasterToPolygons(r,function(x) x == 1,dissolve=T)
I use a function to only get pixels with value 1. Also I dissolve the polygons to not have single pixel polygons but rather an area. See rasterToPolygons for other options.
And now plot the borders and the new polygon together:
plot(shp)
plot(pol,col='red',add=T)
And there you have it, a polygon of the distribution. This is the console output:
> pol
class : SpatialPolygonsDataFrame
features : 1
extent : -62.98971, -43.48971, -20.23512, -1.735122 (xmin, xmax, ymin, ymax)
coord. ref. : NA
variables : 1
names : layer
min values : 1
max values : 1
Hope that helps!
Edit: Bonus answer
You have to be clear, that the pixelized boundaries of your polygon(s) represent an accurate representation of your data. So any change to that means a loss of precision. Now, depending on your purpose, that might not matter.
There's multiple ways to achieve it, either at the raster side with disaggregating and smoothing/filtering etc. or at the polygon side, where you can apply specific filters to the polygons like this.
If it's purely aesthetic, you can try gSimplify from the rgeos package:
# adjust tol for smoothness
pol_sm <- gSimplify(pol,tol=0.5)
plot(pol)
lines(pol_sm,col='red',lwd=2)

How to create a raster brick with rasters of different extents?

I am new in R so this question is very basic but I have been struggling with it and could not find a solution that worked. I want to create a raster brick from some landsat images of the same area.
They were downloaded in HDF-EOS format, and I used the Modis Reprojection Tool to convert them to .tif.
The resulting rasters have the same projection, but differ in their extent, resolution and origin.
I tried several approaches, summarized here below:
defining a subset extent manually and subsetting all the rasters. Then trying to make a brick with the subset rasters
Resampling the rasters, to give them the same number of columns and rows. Ideally that would ensure the raster cells are aligned and can be put into a raster brick. This option created a brick where rasters had no values, they were empty.
I am wondering what is the concept I should follow to correct the extent. Would it be correct (and efficient) to create an empty raster that I would fill in later with the values of the imported landsat image? Can you see where I am making a mistake?
In case it is relevant, I am working on a Mac OSX Version 10.9.1, and using rgdal version 0.8-14
Any help will be very appreciated!
Thankyou
I add here the code I have been using:
# .tif files have been creating using the Modis Reprojection Tool. Input
# files used for this Tool was LANDSAT HDF-EOS imagery.
library(raster)
library(rgdal)
setwd()=getwd()
# Download the files from dropbox:
dl_from_dropbox <- function(x, key) {
require(RCurl)
bin <- getBinaryURL(paste0("https://dl.dropboxusercontent.com/s/", key, "/", x),
ssl.verifypeer = FALSE)
con <- file(x, open = "wb")
writeBin(bin, con)
close(con)
message(noquote(paste(x, "read into", getwd())))
}
dl_from_dropbox("lndsr.LT52210611985245CUB00-vi.NDVI.tif", "qb1bap9rghwivwy")
dl_from_dropbox("lndsr.LT52210611985309CUB00-vi.NDVI.tif", "sbhcffotirwnnc6")
dl_from_dropbox("lndsr.LT52210611987283CUB00-vi.NDVI.tif", "2zrkoo00ngigfzm")
# Create three rasters
tif1 <- "lndsr.LT52210611985245CUB00-vi.NDVI.tif"
tif2 <- "lndsr.LT52210611985309CUB00-vi.NDVI.tif"
tif3 <- "lndsr.LT52210611987283CUB00-vi.NDVI.tif"
r1 <- raster(tif1, values=TRUE)
r2 <- raster(tif2, band=1, values=TRUE)
r3 <- raster(tif3, band=1, values=TRUE)
### Display their properties
# projection is identical for the three rasters
projection(r1)
# "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
projection(r2)
projection(r3)
# Extents are different
extent(r1)
# class : Extent
# xmin : -45.85728
# xmax : -43.76855
# ymin : -2.388705
# ymax : -0.5181549
extent(r2)
# class : Extent
# xmin : -45.87077
# xmax : -43.78204
# ymin : -2.388727
# ymax : -0.5208711
extent(r3)
# class : Extent
# xmin : -45.81952
# xmax : -43.7173
# ymin : -2.405129
# ymax : -0.5154312
# origin differs for all
origin(r1)
# 5.644590e-05 -8.588605e-05
origin(r2)
# 0.0001122091 -0.0001045107
origin(r3)
# 6.949976e-05 -5.895945e-05
# resolution differs for r2
res(r1)
# 0.0002696872 0.0002696872
res(r2)
# 0.0002696875 0.0002696875
res(r3)
# 0.0002696872 0.0002696872
## Try different approaches to create a raster brick
# a- define a subset extent, and subset all the rasters
plot(r1, main="layer1 NDVI")
de <- drawExtent(show=TRUE, col="red")
de
# class : Extent
# xmin : -45.36159
# xmax : -45.30108
# ymin : -2.002435
# ymax : -1.949501
e <- extent(-45.36159,-45.30108,-2.002435,-1.949501)
# Crop each raster with this extent
r1c <- crop(r1,e)
r2c <- crop(r2,e)
r3c <- crop(r3,e)
# Make raster brick
rb_a <- brick(r1c,r2c,r3c)
# Error in compareRaster(x) : different extent
# b- Resample each raster
s <- raster(nrow=6926, ncol=7735) # smallest nrow and ncol among r1,r2 and r3
r1_res <- resample(r1,s, method="ngb")
r2_res <- resample(r2,s, method="ngb")
r3_res <- resample(r3,s, method="ngb")
# Resampling gives for the three rasters the following message:
# Warning message:
# In .local(x, y, ...) :
# you are resampling y a raster with a much larger cell size,
# perhaps you should use "aggregate" first
# Make raster brick
rb_c <- brick(r1, r2, r3)
# Error in compareRaster(x) : different extent
here are some things to help you out. Since I don't have your .tif files just some hints. Have you checked the extent on your raster s? It's the size of the world, with just those columns its cells are extremely large. So you have to add an extent to your raster before resampling it. From your info I did something like this:
# create an extent that includes all your data
e<-extent(-46, -43, -2, -0.6)
# create a raster with that extent, and the number of rows and colums to achive a
# similar resolution as you had before, you might have to do some math here....
# as crs, use the same crs as in your rasters before, from the crs slot
s<-raster(e, nrows=7000, ncols=7800, crs=r1#crs)
# use this raster to reproject your original raster (since your using the same crs,
# resample should work fine
r1<-resample(r1, s, method="ngb")
Happy Holidays,
Ben
PS a better way to find your desired extent & resolution:
# dummy extent from your rasters, instead use lapply(raster list, extent)
a<-extent(-45.85728, -43.76855, -2.388705, -0.5181549)
b<-extent(-45.87077, -43.78204, -2.388727, -0.5208711)
c<-extent(-45.81952 ,-43.7173 , -2.405129 ,-0.5154312)
extent_list<-list(a, b, c)
# make a matrix out of it, each column represents a raster, rows the values
extent_list<-lapply(extent_list, as.matrix)
matrix_extent<-matrix(unlist(extent_list), ncol=length(extent_list)
rownames(matrix_extent)<-c("xmin", "ymin", "xmax", "ymax")
# create an extent with the extrem values of your extent
best_extent<-extent(min(matrix_extent[1,]), max(matrix_extent[3,]),
min(matrix_extent[2,]), max(matrix_extent[4,]))
# the range of your extent in degrees
ranges<-apply(as.matrix(best_extent), 1, diff)
# the resolution of your raster (pick one) or add a desired resolution
reso<-res(r1)
# deviding the range by your desired resolution gives you the number of rows and columns
nrow_ncol<-ranges/reso
# create your raster with the following
s<-raster(best_extent, nrows=nrow_ncol[2], ncols=nrow_ncol[1], crs=r1#crs)

Resources