Extracting climate data from WorldClim

I have a basic question, but I don't understand what I'm doing wrong. I'm trying to extract climate data from WorldClim with the geodata package, when I try to create the object of the class SpatialPoints. I get that the crs does not exist

This is the code I have tried:

library(sp)
library(raster)
library(geodata)

r <- worldclim_global(var = "bio", res = 2.5, path= tempdir())
r <- r[[c(1,12)]]
names(r) <- c("Temp","Prec")


lats <- c(14.628434, 9.396111)
lons <- c(-90.5227, -11.72975)
coords <- data.frame(x=lons, y = lats)

points <- SpatialPoints(coords, proj4string = r@crs)

At this point I receive this error:

Error in initialize(value, ...) : 
  no slot of name "crs" for this object of class "SpatRaster"

and if I change it to cpp I get this error:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'obj' in selecting a method for function 'bbox': assignment of an object of class “Rcpp_SpatRaster” is not valid for slot ‘proj4string’ in an object of class “Spatial”; is(value, "CRS") is not TRUE

I would be grateful for any ideas on how to solve this problem.

I tried to download the data from getData from raster, but it doesn't work anymore, I don't know if this is the problem.

Upvotes: 1

Views: 536

Answers (1)

UseR10085
UseR10085

Reputation: 8198

The problem is that the r is a SpatRaster object while your points is a SpatialPoints object. You can make points as SpatVector using the following code

library(geodata)

r <- worldclim_global(var = "bio", res = 2.5, path= tempdir())
r <- r[[c(1,12)]]
r
#> class       : SpatRaster 
#> dimensions  : 4320, 8640, 2  (nrow, ncol, nlyr)
#> resolution  : 0.04166667, 0.04166667  (x, y)
#> extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#> sources     : wc2.1_2.5m_bio_1.tif  
#>               wc2.1_2.5m_bio_12.tif  
#> names       :      Temp,  Prec 
#> min values  : -54.75917,     0 
#> max values  :  31.16667, 11246
 
names(r) <- c("Temp","Prec")


lats <- c(14.628434, 9.396111)
lons <- c(-90.5227, -11.72975)
coords <- data.frame(x=lons, y = lats)

points <- vect(coords, geom=c("x", "y"), crs="+proj=longlat +datum=WGS84")

SpatialPoints is not compatible with SpatRaster object. To associate average temperature and precipitation for each of your coordinates, you have to use

extract(r, points, xy=T)

#> ID     Temp Prec         x         y
#> 1  1 19.59883 1249 -90.52083 14.645833
#> 2  2 25.94717 2508 -11.72917  9.395833

Upvotes: 3

Related Questions