I'm downloading an average temperature from WorldClim for a set of specific locations (lat-long) using getData
from raster
package. The raw values are around 100. Then I apply gain()
of 0.1 to all of them and R returns values of 1.0, while it should be 10.0. The problem applies only to WorldClim resolution 10 degrees (at 2.5 the temperature values are correct).
Here's what I'm doing:
library(raster)
library(sp)
Some random data
x <- runif(10, -72.85, -72.78)
y <- runif(10, 44.5, 44.6)
coords <- data.frame(x, y)
Downloading WorldClim data, applying gain of 0.1, binding lat-long and climate data in one data frame
r <- getData("worldclim",var="tmean",res=10)
gain(r) <- 0.1
points <- SpatialPoints(coords, proj4string = r@crs)
values <- extract(r,points)
df <- cbind.data.frame(coordinates(points),values)
Does anyone know why gain 0.1 changes 100 into 1.0 instead of 10.0?
Cheers
You have uncovered a bug in the current version of "raster". This bug crept in because in that version methods from "terra" have replaced methods from "rgdal" (because that package will be retired). What happens in your example is that the scale and offset were applied twice. This problem goes away if you install terra version 1.6-46 and raster version 3.6-8. These are currently the development versions. On windows they can be installed with
install.packages('terra', repos='https://rspatial.r-universe.dev')
install.packages('raster', repos='https://rspatial.r-universe.dev')
With these versions, I see:
library(raster)
#Loading required package: sp
coords <- data.frame(5, 52)
r <- getData("worldclim",var="tmean",res=10)
#Warning message:
#In getData("worldclim", var = "tmean", res = 10) :
# getData will be removed in a future version of raster
#. Please use the geodata package instead
extract(r, coords)
# tmean1 tmean2 tmean3 tmean4 tmean5 tmean6 tmean7 tmean8 tmean9 tmean10 tmean11 tmean12
#[1,] 23 27 50 72 121 150 167 168 144 108 63 34
gain(r) <- 0.1
extract(r, coords)
# tmean1 tmean2 tmean3 tmean4 tmean5 tmean6 tmean7 tmean8 tmean9 tmean10 tmean11 tmean12
#[1,] 2.3 2.7 5 7.2 12.1 15 16.7 16.8 14.4 10.8 6.3 3.4
sessionInfo()
#raster_3.6-8
#terra_1.6-46
Also, the suggestion about using the geodata package instead of getData is important. You are using obsolete data.