Issue
I'd like to get the average temperature and precipitation for the state of Ceara in Brazil; I made a cropped area on the map as:
and I used the center lat/lon as lat=-5.49839
and lon=-39.32062
I got the caps of latitude and longitude as latinicial=-7.24614
(minimum latitude), latfinal=-3.76140
(maximum latitude), longinicial=-40.38084
(minimum longitude) and longfinal=-38.77385
(maximum longitude) then I've simulated a uniformly distributed temperature for both latitude and longitude which lies in their maxima and minima.
My code is given as follows:
library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(dismo)
library(rgdal)
library(sf)
d=getData('worldclim',lat=-5.49839,lon=-39.32062,res=0.5,var='bio')
latinicial=-7.24614
latfinal=-3.76140
longinicial=-40.38084
longfinal=-38.77385
latitude=runif(100,latinicial,latfinal)
longitude=runif(100,longinicial,longfinal)
coord=data.frame(latitude,longitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1,12)]]
names(d)=c("Temp","Prec")
extract(d,points)
But when I run it, I got NA values for all rows even though I'm showing you only 4 rows:
So, I'd like to know what happened to it. Why do I get NA values?
Solution
The problem is with the order of longitude and latitude in coords
. When you put coords
into SpatialPoints
, it expects the order to be longitude
then latitude
, but you have it reversed. Once you fix that, then it will extract the data correctly. All the code above coord
works fine. Also, if you are going to run this code multiple times, then I would recommend using set.seed
. This will allow you to get the same values every time when you run the runif
statements.
library(raster)
library(sp)
set.seed(243)
d = getData(
'worldclim',
lat = -5.49839,
lon = -39.32062,
res = 0.5,
var = 'bio'
)
latinicial = -7.24614
latfinal = -3.76140
longinicial = -40.38084
longfinal = -38.77385
latitude = runif(100, latinicial, latfinal)
longitude = runif(100, longinicial, longfinal)
coord = data.frame(longitude, latitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1, 12)]]
names(d) = c("Temp", "Prec")
extract(d, coord)
Output
head()
Temp Prec
[1,] 239 655
[2,] 267 832
[3,] 256 541
[4,] 269 740
[5,] 242 784
[6,] 233 981
Answered By - AndrewGB Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.