Changing the raster spatial extent in R - r

I have two rasters and I want to make the spatial extent of one to another. Then save it as a new raster. I used following code. However, I cannot save the 2013 images with new spatial extent as a new raster. Any guidance is greatly appreciated.
raster_2013 <- raster("avgt2013.tif")
extent(raster_2013)
class : Extent
xmin : 112.91
xmax : 153.64
ymin : -43.75
ymax : -9
> res(raster_2013)
[1] 0.01 0.01
>
> raster_2015 <- raster("avgt2015.tif")
> extent(raster_2015)
class : Extent
xmin : 112
xmax : 154
ymin : -44
ymax : -9
> res(raster_2015)
[1] 0.01 0.01
>
> e <- extent(112, 154, -44, -9)
>
> ex = extent(raster_2015)
> r2 = crop(raster_2013, ex)
>
>
> new_2013 <- alignExtent(e, raster_2013, snap='near')
> str(new_2013)
Formal class 'Extent' [package "raster"] with 4 slots
..# xmin: num 112
..# xmax: num 154
..# ymin: num -44
..# ymax: num -9
>
> rc <- crop(raster_2013, e, snap='near')
> extent(rc)
class : Extent
xmin : 112.91
xmax : 153.64
ymin : -43.75
ymax : -9

First, please make a simple reproducible example to ask a question.
library(raster)
set.seed(11)
raster_2013 = raster(ext=extent(112.91, 153.64, -43.75, -9), res=c(0.01, 0.01))
raster_2013[] = rnorm(ncell(raster_2013))
raster_2015 = raster(ext=extent(112, 154, -44, -9), res=c(0.01, 0.01))
raster_2015[] = rnorm(ncell(raster_2015))
Then, there are several issues with your code.
In your case, alignExtent is useless since the two rasters have the same resolution and their extents correspond with regards to this resolution.
If your goal is to give the extent of raster_2015 to raster_2013, you need to realize that extent(raster_2015) is shorter (smaller) with respect to xmin, but larger or equal elsewhere. So cropping alone will just affect xmin of raster_2013. You first need to extend and second to crop in order to have the exact same extent:
new_2013 <- crop(extend(raster_2013, raster_2015), raster_2015)
all.equal(extent(raster_2015), extent(new_2013))
#[1] TRUE
As #Geo-sp mentions, you can also resample raster_2013, but you would typically use this if the rwo rasters are not aligned (and be aware that it would, in such case, result in modified data due to the interpolation). Here, since they are, it would give the same result as crop(extend()), but it would be much slower and more resource-consuming:
system.time(new_2013 <- crop(extend(raster_2013, raster_2015), raster_2015))
# user system elapsed
# 0.676 0.036 0.712
system.time(new_2013_res <- resample(raster_2013, raster_2015))
# user system elapsed
# 10.324 0.536 10.869
all.equal(new_2013, new_2013_res)
# [1] TRUE
Finally, in order to save it, well... you can use writeRaster, as reading the documentation would have lead you to ;-)
writeRaster(new_2013, "raster_2013_extent2015.grd")

Related

stack geotiff with stars 'along' when 'band' dimension contains band + time information

I have a timeseries of geotiff files I'd like to stack in R using stars. Here's the first two:
urls <- paste0("/vsicurl/",
"https://sdsc.osn.xsede.org/bio230014-bucket01/neon4cast-drivers/",
"noaa/gefs-v12/cogs/gefs.20221201/",
c("gep01.t00z.pgrb2a.0p50.f003.tif", "gep01.t00z.pgrb2a.0p50.f006.tif"))
library(stars)
stars::read_stars(urls, along="time")
Errors with:
Error in c.stars_proxy(`3` = list(gep01.t00z.pgrb2a.0p50.f003.tif = "/vsicurl/https://sdsc.osn.xsede.org/bio230014-bucket01/neon4cast-drivers/noaa/gefs-v12/cogs/gefs.20221201/gep01.t00z.pgrb2a.0p50.f003.tif"), :
don't know how to merge arrays: please specify parameter along
Context: bands contain both time+band info
This fails because the dimensions do not match, which happens because the files have concatenated temporal information into the band names:
x<- lapply(urls, read_stars)
x
produces:
[[1]]
stars object with 3 dimensions and 1 attribute
attribute(s), summary of first 1e+05 cells:
Min. 1st Qu. Median Mean 3rd Qu. Max.
gep01.t00z.pgrb2a.0p50.f003.ti... 50026.01 98094.81 101138 98347.42 101845.2 104605.2
dimension(s):
from to offset delta refsys point
x 1 720 -180.25 0.5 Coordinate System importe... FALSE
y 1 361 90.25 -0.5 Coordinate System importe... FALSE
band 1 8 NA NA NA NA
values x/y
x NULL [x]
y NULL [y]
band PRES:surface:3 hour fcst,...,DLWRF:surface:0-3 hour ave fcst
[[2]]
stars object with 3 dimensions and 1 attribute
attribute(s), summary of first 1e+05 cells:
Min. 1st Qu. Median Mean 3rd Qu. Max.
gep01.t00z.pgrb2a.0p50.f006.ti... 50029.83 98101.83 101170.6 98337.52 101825 104588.2
dimension(s):
from to offset delta refsys point
x 1 720 -180.25 0.5 Coordinate System importe... FALSE
y 1 361 90.25 -0.5 Coordinate System importe... FALSE
band 1 8 NA NA NA NA
values x/y
x NULL [x]
y NULL [y]
band PRES:surface:6 hour fcst,...,DLWRF:surface:0-6 hour ave fcst
Note the band names would align except for the existence of the timestamp being tacked on, e.g. PRES:surface:3 hour fcst vs PRES:surface:6 hour fcst.
How can I best read in these files so that I have dimensions of x,y,band, and time in my stars object?
alternatives: terra?
How about terra? Note that terra is happy to read these files in directly, but treats this as 16 unique bands. Can I re-align that so that I have the original 8 bands along a new "time" dimension? (I recognize stars emphasizes 'spatio-temporal', maybe the such a cube is out of scope to terra?) Also note that terra for some reason mangles the timestamp in these band names:
x <- terra::rast(urls)
x
class : SpatRaster
dimensions : 361, 720, 16 (nrow, ncol, nlyr)
resolution : 0.5, 0.5 (x, y)
extent : -180.25, 179.75, -90.25, 90.25 (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat Coordinate System imported from GRIB file
sources : gep01.t00z.pgrb2a.0p50.f003.tif (8 layers)
gep01.t00z.pgrb2a.0p50.f006.tif (8 layers)
names : PRES:~ fcst, TMP:2~ fcst, RH:2 ~ fcst, UGRD:~ fcst, VGRD:~ fcst, APCP:~ fcst, .
With terra it is pretty easy to make a time-series for each variable as I show below.
urls <- paste0("/vsicurl/",
"https://sdsc.osn.xsede.org/bio230014-bucket01/neon4cast-drivers/",
"noaa/gefs-v12/cogs/gefs.20221201/",
c("gep01.t00z.pgrb2a.0p50.f003.tif", "gep01.t00z.pgrb2a.0p50.f006.tif"))
library(terra)
r <- rast(urls)
Extract two variables of interest
nms <- names(r)
tmp <- r[[grep("TMP", nms)]]
rh <- r[[grep("RH", nms)]]
# set time
tm <- as.POSIXct("2022-12-01", tz="GMT") + c(3,6) * 3600
time(rh) <- tm
time(tmp) <- tm
And you could combine them into a SpatRasterDatset like this:
s <- sds(list(tmp=tmp, rh=rh))
An alternative path to get to the same point would be to start with a SpatRasterDataset and subset it.
sd <- sds(urls)
nl <- 1:length(sd)
nms <- names(sd[1])
tmp2 <- rast(sd[nl, grep("TMP", nms)])
time(tmp2) <- tm
rh2 <- rast(sd[nl, grep("RH", nms)])
time(rh2) <- tm
I made the subsetting work a little nicer in terra version 1.7-5
urls <- paste0("/vsicurl/",
"https://sdsc.osn.xsede.org/bio230014-bucket01/neon4cast-drivers/",
"noaa/gefs-v12/cogs/gefs.20221201/", c("gep01.t00z.pgrb2a.0p50.f003.tif", "gep01.t00z.pgrb2a.0p50.f006.tif"))
library(terra)
#terra 1.7.5
sd <- sds(urls)
tmp <- sd[,2]
tmp
#class : SpatRaster
#dimensions : 361, 720, 2 (nrow, ncol, nlyr)
#resolution : 0.5, 0.5 (x, y)
#extent : -180.25, 179.75, -90.25, 90.25 (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat Coordinate System imported from GRIB file
#sources : gep01.t00z.pgrb2a.0p50.f003.tif
# gep01.t00z.pgrb2a.0p50.f006.tif
#names : TMP:2 m above g~Temperature [C], TMP:2 m above g~Temperature [C]
#unit : C, C
#time : 2022-12-01 03:00:00 to 2022-12-01 06:00:00 UTC
As for the layer names containing the forecast time, that is just because that is what is in the tif metadata. It looks like that was a decision made when they were created from the original GRIB files.
The latitude extent going beyond the north and south poles is an interesting feature of this dataset.
Just wanted to share some additional possible solutions for comparison. With larger numbers of files some of these differences become more relevant. this expands a bit beyond my original question.
terra
Prof Hijmans gives a very nice solution in terra. He also asked about the original upstream sources, which I didn't explain properly -- these are originally GRIB files for NOAA GEFS forecast.
Notably, we can work directly from the GRIB files. GEFS is a 35-day forecast, so let's try going more than 6 hrs into the future:
library(terra)
# original GRIB sources, AWS mirror
gribs <- paste0("/vsicurl/https://noaa-gefs-pds.s3.amazonaws.com/gefs.20220314/00/atmos/pgrb2ap5/geavg.t00z.pgrb2a.0p50.f",
stringr::str_pad(seq(3,240,by=3), 3, pad="0"))
bench::bench_time({
cube <- terra::sds(gribs)
})
cube[1,63] |> plot()
very nice!
gdalcubes
gdalcubes is another package that can also leverage the gdal virtual filesystem when working with these large-ish remote files. It also lets us define an abstract cube at potentially a different resolution in space & time than the original sources (averaging or interpolating). lazy operations mean this may run a bit faster(?)
library(gdalcubes)
date <- as.Date("2023-01-26")
date_time = date + lubridate::hours(seq(3,240,by=3))
# USA box
v <- cube_view(srs = "EPSG:4326",
extent = list(left = -125, right = -66,top = 49, bottom = 25,
t0= as.character(min(date_time)), t1=as.character(max(date_time))),
dx = 0.5, dy = 0.5, dt = "PT3H")
gribs <- paste0("/vsicurl/https://noaa-gefs-pds.s3.amazonaws.com/gefs.20220314/00/atmos/pgrb2ap5/geavg.t00z.pgrb2a.0p50.f",
stringr::str_pad(seq(3,240,by=3), 3, pad="0"))
bench::bench_time({
cube <- gdalcubes::create_image_collection(gribs, date_time = date_time)
})
bench::bench_time({
raster_cube(cube, v) |>
select_bands("band63") |> # tempearture
animate(col = viridisLite::viridis, nbreaks=50, fps=10, save_as = "temp.gif")
})
stars
didn't translate a full stars example, but here at least is the band name correction; a bit more cumbersome than the examples above.
urls <- paste0("/vsicurl/",
"https://sdsc.osn.xsede.org/bio230014-bucket01/neon4cast-drivers/",
"noaa/gefs-v12/cogs/gefs.20221201/",
c("gep01.t00z.pgrb2a.0p50.f003.tif", "gep01.t00z.pgrb2a.0p50.f006.tif"))
library(stars)
#stars::read_stars(urls, along="time") # no luck!
## grab unstacked proxy object for each geotiff
x <- lapply(urls, read_stars)
# extract band-names-part
band_names <- st_get_dimension_values(x[[1]], "band") |>
stringr::str_extract("([A-Z]+):") |>
str_remove(":")
# apply corrected band-names
x1 <- lapply(x, st_set_dimensions, "band", band_names)
# at last, we can stack into a cube:
x1 <- do.call(c, c(x1, along="time"))
# and add correct date timestamps to the new time dimension
dates <- as.Date("2022-12-01") + lubridate::hours(c(3,6))
x1 <- st_set_dimensions(x1, "time", dates)
x1

How to overlay two Rasters using ifelse (Conditional Statements) in R?

I have two rasters (images), and want to overlay them using this code:
# Getting the images
library(raster)
URL1 <- "https://www.dropbox.com/s/6jjz7ou1skz88wr/raster_1.tif?dl=1"
URL2 <- "https://www.dropbox.com/s/d5xuixohjqfnfze/raster_2.tif?dl=1"
download.file(URL1, destfile=paste0(getwd(),"/", "raster_1.tif"), method="auto", mode="wb", timeout="6000")
download.file(URL2, destfile=paste0(getwd(),"/", "raster_2.tif"), method="auto", mode="wb", timeout="6000")
# Reading the images
raster_1 <- raster(list.files(pattern="raster_1.tif$"))
raster_2 <- raster(list.files(pattern="raster_2.tif$"))
# Overlaying
myFun <- function(x,y){ifelse(x==0 && y==0, 0, ifelse(x==1 && y==0, 2, ifelse(x==1 && y>0, y)))}
( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )
### R gives this error
Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun, :
cannot use this formula, probably because it is not vectorized
I would be very grateful if anyone could help me.
Thanks.
You need a function that only uses vectorized operators. This is case where Boolean arithmetic should both succeed and be more efficient
myFun <- function(x,y){ 0*(x==0 && y==0)+
2*(x==1 && y==0)+
y*(x==1 && y>0) }
There are some edge cases that do not appear covered. Can x ever be a value other than exactly 0 or 1? Can y ever be negative?
After running my version I get:
> ( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )
class : RasterLayer
dimensions : 2958, 1642, 4857036 (nrow, ncol, ncell)
resolution : 500, 500 (x, y)
extent : -171063.8, 649936.2, 5317253, 6796253 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
data source : in memory
names : layer
values : 0, 14751 (min, max)
I didn't think I would need to use Vectorize around myFun,enter code here but the results seems more likely to be correct when I leave it in the call to overlay:
> Hmisc::describe(values(res))
values(res)
n missing distinct Info Mean Gmd .05 .10 .25
3222508 1634528 1502 0.727 4918 6403 0 0 0
.50 .75 .90 .95
0 13898 14082 14168
Value 0 13000 13200 13400 13600 13800 14000 14200 14400
Frequency 2089448 67 578 10515 69031 249817 523241 226628 46191
Proportion 0.648 0.000 0.000 0.003 0.021 0.078 0.162 0.070 0.014
Value 14600 14800
Frequency 6876 116
Proportion 0.002 0.000
When I took out the Vectorize step I did not get an error but I got all zeros, instead.
It is not clear what you really are trying to achieve, and there might be better solutions. In your example data, Y (raster_2) has no values of zero. That suggest that you want the values of raster_2 where raster_1 is not 0? That can be achieved like this:
m <- mask(raster_2, raster_1, maskvalue=0)
I think that 42-'s myFun has a problem in that it returns 0 when none of the conditions are true, specifically when (x == 0 & y > 0)
To make it work with overlay, replace the && with &
myFunV <- function(x,y){
0*(x==0 & y==0)+
2*(x==1 & y==0)+
y*(x==1 & y>0) }
res <- overlay(raster_1, raster_2, fun = myFunV)
(but, again, I doubt that this is good approach for your needs)

Cropping raster to minimum extent not working in R

I am writing a script that will take any three rasters, and crop them to the minimum possible extent. All three rasters will have the same resolution and projection. However, cropping to the minimum extent does not change the extents for the three rasters. I've tried setExtent and the same thing happens. If anyone can give suggestions I would really appreciate it. Here is sample code:
library(raster)
#Projection of all three rasters
newproj<- "+proj=utm +zone=4 +datum=WGS84 +units=m +no_defs +ellps=WGS84
+towgs84=0,0,0"
#Create three rasters with varying extents
raster1p<- raster(crs = newproj)
extent(raster1p)<- c(531247, 691847, 7856684, 7987884)
res(raster1p)<- c(100, 100)
values(raster1p)<- NA
raster2p<- raster(crs = newproj)
extent(raster2p)<- c(533550.8, 646550.8, 7881307, 7973807)
res(raster2p)<- c(100, 100)
values(raster2p)<- NA
raster3p<- raster(crs = newproj)
extent(raster3p)<- c(525739, 689839, 7857305, 7996505)
res(raster3p)<- c(100, 100)
values(raster3p)<- NA
#Find minimum extent
xmin1<- c(xmin(extent(raster1p)), xmin(extent(raster2p)), xmin(extent(raster3p)))
xmax1<- c(xmax(extent(raster1p)), xmax(extent(raster2p)), xmax(extent(raster3p)))
ymin1<- c(ymin(extent(raster1p)), ymin(extent(raster2p)), ymin(extent(raster3p)))
ymax1<- c(ymax(extent(raster1p)), ymax(extent(raster2p)), ymax(extent(raster3p)))
xmin_new<- min(xmin1)
xmax_new<- min(xmax1)
ymin_new<- min(ymin1)
ymax_new<- min(ymax1)
newextent=c(xmin_new, xmax_new, ymin_new, ymax_new)
#Crop rasters to minimum extent
crop(raster1p, newextent)
crop(raster2p, newextent)
crop(raster3p, newextent)
#Compare extents
extent_check<- c(extent(raster1p), extent(raster2p), extent(raster3p))
However, when I look at the extent_check to see if the extents now match, I see that the extents have not changed at all:
> extent_check
[[1]]
class : Extent
xmin : 531247
xmax : 691847
ymin : 7856684
ymax : 7987884
[[2]]
class : Extent
xmin : 533550.8
xmax : 646550.8
ymin : 7881307
ymax : 7973807
[[3]]
class : Extent
xmin : 525739
xmax : 689839
ymin : 7857305
ymax : 7996505
Any idea what I could be doing wrong? Thank you for your time
I think it is not so much about doing something wrong, but rater a misconception (although there is a mistake in your code).
Example data
library(raster)
prj <- "+proj=utm +zone=4 +datum=WGS84"
r1 <- raster(res=100, ext=extent(c(531247, 691847, 7856684, 7987884)), crs=prj, vals=NA)
r2 <- raster(res=100, ext=extent(c(533550.8, 646550.8, 7881307, 7973807)), crs=prj, vals=NA)
r3 <- raster(res=100, ext=extent(c(525739, 689839, 7857305, 7996505)), crs=prj, vals=NA)
Find the "minimum extent"
e <- intersect(intersect(extent(r1), extent(r2)), extent(r3))
Note that the result is different from yours because you use
xmin_new <- min(xmin1) and ymin_new <- min(ymin1)
Where it should be
xmin_new <- max(xmin1) and ymin_new <- max(ymin1)
Now crop
r1e <- crop(r1, e)
r2e <- crop(r2, e)
r3e <- crop(r3, e)
Inspect the resulting extents
t(sapply(c(r1e, r2e, r3e), function(i) as.vector(extent(i))))
# [,1] [,2] [,3] [,4]
#[1,] 533547.0 646547.0 7881284 7973784
#[2,] 533550.8 646550.8 7881307 7973807
#[3,] 533539.0 646539.0 7881305 7973805
They are not exactly the same, because that is not possible because the rasters do not align. Their "origins" are different
t(sapply(c(r1e, r2e, r3e), origin))
# [,1] [,2]
#[1,] 47.0 -16
#[2,] -49.2 7
#[3,] 39.0 5
To make them align, you would need to do something like this
r1e <- crop(r1, e)
r2e <- resample(r2, r1e)
r3e <- resample(r3, r1e)
t(sapply(c(r1e, r2e, r3e), function(i) as.vector(extent(i))))
# [,1] [,2] [,3] [,4]
#[1,] 533547 646547 7881284 7973784
#[2,] 533547 646547 7881284 7973784
#[3,] 533547 646547 7881284 7973784

Adding point locations to a 3D DEM plot in R

I have some point locations which include UTMs and Elevation as a data frame
I also have a DEM layer.
I have figured out how to plot the DEM in 3D using plot3D in rgl.
I can also plot the points in 3D using points3d.
I have been able to put them in the same plot using points3d with add=TRUE
however the points and DEM are radically far away from each other.
In the code below I also tried to change this to a spatial data frame but rgl doesn't seem to like that.
Is it possible to plot them together with the points laying over the DEM?
I have searched and searched for a solution to this.
Here is the R code I have used so far:
> library(raster)
> library(rgdal)
> library(maptools)
> library(rgeos)
> library(lattice)
> library(latticeExtra)
> library(sp)
> library(rasterVis)
> library(rgl)
>
> # taking data read from a .csv of UTM and elevation values
>
> Points.Sp <- data.frame(Points=Rawdata$PointName, UTM.N=Rawdata$UTM.N, UTM.W=Rawdata$UTM.W, Elevation=Rawdata$Elevation)
> Points.Sp <- unique(Points.Sp) #weeding out duplicates
> Points.Sp <- Points.Sp[,c(3,2,4)] #getting rid of point names # I realize this looks messy but it gets what I want
> head(Points.Sp)
UTM.W UTM.N Elevation
1 275815 3879223 1340
8 274813 3879727 1325
29 275312 3879727 1258
45 275812 3879724 1169
66 276313 3879727 1067
75 276813 3879727 1208
>
> dem.in <- raster("D:/Thesis/SouthernApps/Coweeta/Coweeta/DEM_30m_wgs84.img") # reading in DEM
> plot(dem.in) # check in 2D # takes a long time very large, need to crop
>
> dem.crop <- crop(dem.in, c(272000, 282000, 3878000, 3884000))
> plot(dem.crop) # check in 2D, looks good.
>
> plot3D(dem.crop) # plot in 3D looks like exactly what I want
>
> points3d(Points.Sp, pch=19, cex=2, col="black", add=TRUE) # adds the points to plot but in wrong place
>
> #attempting to set a CRS in case this is the problem.
> coordinates(Points.Sp)=c(1,2)
> proj4string(Points.Sp)=CRS("++proj=utm +zone=17") # set CRS
> str(Points.Sp)
Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
..# data :'data.frame': 71 obs. of 1 variable:
.. ..$ Elevation: int [1:71] 1340 1325 1258 1169 1067 1208 1256 1089 1031 959 ...
..# coords.nrs : num [1:2] 1 2
..# coords : num [1:71, 1:2] 275815 274813 275312 275812 276313 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:71] "1" "8" "29" "45" ...
.. .. ..$ : chr [1:2] "UTM.W" "UTM.N"
..# bbox : num [1:2, 1:2] 274309 3878440 279876 3883732
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "UTM.W" "UTM.N"
.. .. ..$ : chr [1:2] "min" "max"
..# proj4string:Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..# projargs: chr "+proj=utm +zone=17 +ellps=WGS84"
>
> # trying this a different way after setting CRS
> x <- Points.Sp#coords[1:71,1]
> y <- Points.Sp#coords[1:71,2]
> z <- Points.Sp#data$Elevation
> m <- data.frame(x=x,y=y,z=z)
>
> plot3D(dem.crop) #again, plot in 3D looks like exactly what I want
> points3d(m, pch=19, cex=2, col="black", add=TRUE) # still adds the points to plot but in wrong place
This code reproduces the problem.
## define a Raster object
data(volcano)
r <- raster(volcano)
extent(r) <- c(0, 610, 0, 870)
## extract sample points
xy <- sampleRandom(r1, 100, xy = TRUE)
r1<-data.frame(x=seq(0, 500, length=(71)), y=seq(0, 500, length=(71)), z=seq(0,500, length=(71)))
## display them
plot3D(r, adjust = FALSE)
points3d(r1, add=TRUE)
As documented in the help page, both the x-axis and y-axis are adjusted with the z values. You can disable this default setting with adjust = FALSE:
library(rgl)
library(rasterVis)
## define a Raster object
data(volcano)
r <- raster(volcano)
extent(r) <- c(0, 610, 0, 870)
## extract sample points
xy <- sampleRandom(r, 100, xy = TRUE)
## display them
plot3D(r, adjust = FALSE)
points3d(xy)
## define a Raster object
data(volcano)
r <- raster(volcano)
extent(r) <- c(0, 610, 0, 870)
## extract sample points
xy <- sampleRandom(r1, 100, xy = TRUE)
#must extract the data from the raster and recombine with the xy data.
#I don't know why this is different than simply using the raw values but it
#provides the desired effect.
r1<-data.frame(x=seq(0, 500, length=(71)), y=seq(0, 500, length=(71)))
z<-extract(r, r1)
r1$z<-z
## display them
plot3D(r, adjust = FALSE)
points3d(r1, add=TRUE)
#points now lie flat on 3d image.
Points flush to 3d Image
Image for original problem

Retrieving values from raster into another raster with different extent and resolution

I got a raster layer 'w_wgs' of climatic values. On the other side, I created an empty raster 'grid'.
I want to assign the values stored in 'w_wgs' into my empty raster grid. I tried merge(), overlay(), over() but these don't work.
How can I do this ? assuming these two rasters don't have the same extent nor resolution (nor equal number of cells, obviously)...but both have the same CRS (WGS84).
Here, a description of my 2 objects :
> extent(w_wgs)
class : Extent
xmin : -64.50344
xmax : 74.07016
ymin : 12.93039
ymax : 72.72534
> res(w_wgs)
[1] 0.01320 0.00895
> res(grid)
[1] 0.08 0.08
> extent(grid)
class : Extent
xmin : 5
xmax : 17.96
ymin : 40
ymax : 50
I think you need to use resample
grid <- resample(w_wgs, grid)
A small example that should be similar to your case:
x <- matrix(1:100, nr = 10, nc = 10)
a <- raster(x)
x2 <- matrix(NA, nr = 3, nc = 3)
b <- raster(x2)
# Manually changing the extent and resolution of b
b#extent#xmax <- 0.5
b#extent#ymin <- 0.3
b <- resample(a, b)
par(mfrow = c(2, 1))
plot(a)
plot(extent(b), add = T)
plot(b)

Resources