R extract raster function not working - r

I am having trouble with the extract function in the raster package. The raster is not empty, but when I perform the extract function all the values come back as NAs. I can plot the points over the raster fine and they show up in the same location.
library(dismo)
library(raster)
#Import CSV File
file <- paste("C:/Michelle/Michelle/R/CuskPA_Sept12_2013_1.csv", sep=" ")
#read file
cusk <- read.table(file, header=TRUE, sep=',')
cusks<- subset(cusks, SlongDD!=0 & SlatDD!=0)
cuskll <-cusks[,24:25]
#import raster
salvar <- raster("C:/Michelle/Michelle/R/Variables/salvar")
ext <-extent(-67.6, -64.9, 41.0, 44.7453)
salvarc <-crop(salvar, ext)
#extract from raster
psalvar <- extract(salvarc, cuskll)
This is what I get when I'm finished the extraction
head(psalvar)
[1] NA NA NA NA NA NA
summary(psalvar)
Mode NA's
logical 3859
The raster does not show up as empty.
> salvar
class : RasterLayer
dimensions : 334, 240, 80160 (nrow, ncol, ncell)
resolution : 0.01121539, 0.01121539 (x, y)
extent : -67.59662, -64.90493, 41.00048, 44.74642 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs
data source : in memory
names : salvar
values : 0.01655413, 2.137321 (min, max)
Here is an example of the lat/longs in the file
head(cuskll)
SlatDD SlongDD
1 44.41533 -66.07883
2 44.41167 -66.07733
3 44.44883 -66.07433
4 44.47067 -66.01217
5 44.47050 -66.01183
6 44.47633 -66.01450

Put longitude first and latitude second

Related

Convert multidimensional NetCDF to Tif in R

I have .nc file sizing around 651 MB with a couple of datasets (daily) (rr_mrg_19810101_20181231_ENACT.nc) data. I need to convert (rr_mrg_19810101_20181231_ENACT.nc) dataset to multiple GeoTIFF (one .tif for each time slice, monthly). Similarly, i want to read the time series. But I found
Error in .local(x, time, ...) :
time must has the same length as the number of layers in RasterBrick][1]
Here is what i did
library(raster)
library(zoo)
library(rts)
TRF = brick("rr_mrg_19810101_20181231_ENACT.nc")
crs(TRF) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84
+towgs84=0,0,0"
Awash_Extent<-c(37,44, 7,12)
Awash_E_resize<- crop(TRF,Awash_Extent)
Awash_Month<-seq(as.Date('1981-01-01'),as.Date('2018-12-31'),by =
"month")
rt <- rts(Awash_E_resize, Awash_Month)
write.rts(Awash_E_resize, filename='Awash_TRF_1981_2018_mon.tif',
overwrite=TRUE)
Can you help me on the issue?
Something as simple as this can do that
library(raster)
b <- brick("rr_mrg_19810101_20181231_ENACT.nc")
writeRaster(b, "timeslice.tif", bylayer=TRUE)
Based on your expanded question:
Read the values with terra (no need for other packages)
library(terra)
TRF = rast("rr_mrg_19810101_20181231_ENACT.nc")
Awash_Extent<-c(37,44, 7,12)
Awash_E_resize<- crop(TRF,Awash_Extent)
I create something similar here:
A <- rast(ext(37,44, 7,12), nlyr=365)
values(A) <- runif(size(A))
terra::time(A) <- seq(as.Date('1981-01-01'), as.Date('1981-12-31'), 1)
Now aggregate by month:
m <- months(time(A))
f <- factor(m, levels=unique(m))
B <- tapp(A, m, fun=sum)
B
#class : SpatRaster
#dimensions : 10, 10, 12 (nrow, ncol, nlyr)
#resolution : 0.7, 0.5 (x, y)
#extent : 37, 44, 7, 12 (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84
#source : memory
#names : January, February, March, April, May, June, ...
#min values : 12.49764, 10.47718, 11.80974, 11.29624, 11.01105, 10.83298, ...
#max values : 18.90536, 16.95743, 20.57114, 18.12099, 18.46543, 18.98500, ...
You could add a filename= argument to tapp, but if you want to save the layers as separate files you can use writeRaster instead. But with terra you need to provide the filenames yourself.
fnames <- paste0("rain_", 1:nlyr(B), ".tif")
writeRaster(B, fnames, overwrite=T)
(there is a warning about file_ext that you can ignore)

How to remove set range of pixel values of DEM in R?

I have a DEM tiff file of a specific region:
> imported_raster
class : RasterLayer
dimensions : 28034, 53030, 1486643020 (nrow, ncol, ncell)
resolution : 0.0008333334, 0.0008333334 (x, y)
extent : 60.85375, 105.0454, 15.95708, 39.31875 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : C:\XX.tif
names : XX
values : -27, 8806 (min, max)
attributes :
ID OBJECTID Value Count
from: 0 1 -27 2
to : 8528 8529 8806 1
I want to set a range of pixel values to NULL. For instance if I want to remove elevation pixel values from -27 to 0 , and 0 to 1000 to NULL. How can I carry this about in R?
In your case this should work well:
library(raster)
library(terra)
# with raster -------------------------------------------------------------
r <- raster()
r[] <- -27:(ncell(r)-28)
new.r <- clamp(r,lower=1000,useValues=F)
# with terra --------------------------------------------------------------
t <- rast(r)
new.t <- clamp(t,lower=1000,values=F)
However, there are several ways to do this, for example with raster::reclassify, terra::classify, but also r[r<1000] <- NA

Apply boot::inv.logit() to a raster in R

I have a Formal Class Raster and I am trying to apply the boot::inv.logit() function to its raster cells, for example:
r1 <- raster(nrows=25, ncols=25, vals=rtnorm(n = 625, .1, .9))
r2 <- boot::inv.logit(r1)
However, when I try that, it retruns an error:
> Error in plogis(x) : Non-numeric argument to mathematical function
If I turn the raster into a matrix, and then back to raster, it gets the job done, but I loose all the other info associated with the "Formal Class Raster" I had at the beginning, which is not ideal:
r2 <- boot::inv.logit(as.matrix(r1))
r2 <- as.raster(r2)
Is there an easy way to either recover the Formal Class Raster info I had before or apply the inv.logit() to the raster without the as.matrix() transformation? Thank you in advance.
If you want to apply the function to the raster, use the calc method from raster:
r2 <- calc(r1,boot::inv.logit)
> r2
# class : RasterLayer
# dimensions : 25, 25, 625 (nrow, ncol, ncell)
# resolution : 14.4, 7.2 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# data source : in memory
# names : layer
# values : 0.07434905, 0.9498965 (min, max)
Alternatively, you can make an empty copy of r1, and just fill in the values coming out of inv.logit:
r2 <- raster(r1)
r2[] <- boot::inv.logit(as.matrix(r1))

Error when extracting values from a rasterBrick or rasterStack

I am having trouble extracting values or a point from a multi band raster of class rasterStack or rasterBrick. 'extract' works well with the individual rasters but posts an error when applied to the rasterStack or brick.
> all.var
class : RasterBrick
dimensions : 89, 180, 16020, 34 (nrow, ncol, ncell, nlayers)
resolution : 2, 2 (x, y)
extent : -179, 181, -89, 89 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names : period_max, pct_signif_periodmax, pct_coi_periodmax, pct_ispos_signif, events_pos_periodmax, events_neg_periodmax, events_pos_all, events_neg_all, maxpower_pos, maxpower_neg, maxpower_events_pos, maxpower_events_neg, maxpower_pos_norm, maxpower_neg_norm, maxpower_events_pos_norm, ...
> point
Lon Lat
1 166.2790 -10.2690
2 26.9000 -33.6000
3 153.6209 -28.7001
4 113.8333 -28.6833
5 153.6335 -28.6591
6 153.5836 -28.4643
7 32.6833 -27.5333
8 32.6880 -27.5260
9 32.6880 -27.5260
10 32.6880 -27.5260
> point.extract<-extract(all.var, point, buffer=50000,na.rm=TRUE,fun=mean)
Error in apply(x, 2, fun2) : dim(X) must have a positive length
This works with individual rasters but fails with stack/brick and elicits an error only when I use a buffer argument.
Here is a working R example that illustrates the error:
library(raster)
b <- brick(nrow=89, ncol=180, nl=34, xmn=-179, xmx=181, ymn=-89, ymx=89, crs="+proj=longlat +datum=WGS84")
b[] <- 1
p <- matrix(c(166.2790,-10.2690,26.9000,-33.6000,153.6209,-28.7001,113.8333,-28.6833,153.6335,-28.6591,153.5836,-28.4643,32.6833,-27.5333,32.6880,-27.5260,32.6880,-27.5260,32.6880,-27.5260), ncol=2, byrow=TRUE)
v <- extract(b, p, buffer=50000, na.rm=TRUE, fun=mean)
That indeed gives the error you reported, probably due a bug in the raster package. Here is a work-around:
v <- extract(b, p, buffer=15000000)
# get the mean for each point (buffer) by layer
vv <- lapply(v, function(x) ifelse(is.matrix(x), colMeans(x, na.rm=TRUE), x))
# combine
do.call(rbind, vv)

How to write a raster with RAT factors in R raster package

I want writeRaster to write the RAT (raster attribute table) that I've built in R.
I'm running R 3.0.1, raster 2.1-49, and rgdal 0.8-10.
My input raster looks like this:
r <-raster("F:/test.img")
class : RasterLayer
dimensions : 3, 3, 9 (nrow, ncol, ncell)
resolution : 30, 30 (x, y)
extent : 347325, 347415, 4301655, 4301745 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=18 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : F:\test.img
names : test
values : 1, 19 (min, max)
I then build my attribute table:
r <- ratify(r)
rat <- levels(r)[[1]]
rat$Pixel_Values <- c(1, 7, 8, 9, 19)
rat$Class_Names <- c("A", "B", "C", "D", "E")
levels(r) <- rat
Which results in a raster with attributes:
r
# class : RasterLayer
# dimensions : 3, 3, 9 (nrow, ncol, ncell)
# resolution : 30, 30 (x, y)
# extent : 347325, 347415, 4301655, 4301745 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=utm +zone=18 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
# data source : F:\test.img
# names : test
# values : 1, 19 (min, max)
# attributes :
# ID Pixel_Values Class_Names
# 1 1 A
# 7 7 B
# 8 8 C
# 9 9 D
# 19 19 E
I then attempt to write my raster together with its RAT:
ratRaster <- "F:/testRat.img"
writeRaster(r, filename=ratRaster, datatype="INT1U", RAT=TRUE, progress="window", overwrite=TRUE)
But when I read it back into R, it becomes apparent that the attributes did not persist:
r2 <- raster(ratRaster)
r2
# class : RasterLayer
# dimensions : 3, 3, 9 (nrow, ncol, ncell)
# resolution : 30, 30 (x, y)
# extent : 347325, 347415, 4301655, 4301745 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=utm +zone=18 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
# data source : F:\testRat.img
# names : testRat
# values : 1, 19 (min, max)
It would be quick and awesome to build RATs in R. How can I create and export the raster and keep the RAT?
Note that if you use raster's native .grd format (see doc, section 3.3) , the RAT table will be saved:
library(raster)
r <- raster(nrows=5, ncols=5)
r[] <- rep(1:5, 5)
r <- ratify(r)
rat <- levels(r)[[1]]
rat$Pixel_Values <- 1:5
rat$Class_Names <- c("A", "B", "C", "D", "E")
levels(r) <- rat
r
writeRaster(r, filename="raster_rat.grd")
Now re-open:
r2 <- raster("raster_rat.grd")
r2
You could always write the RAT as a csv file, then join that data later.
Write your raster as you specified:
writeRaster(r, filename=ratRaster, datatype="INT1U", RAT=TRUE, progress="window", overwrite=TRUE)
Write the attribute data/table/RAT as a .csv file:
write.csv(rat, file="C:\\merp\\rat.csv", row.names = F)
Then you can join this data in another program later.
For example, if exporting from R to ArcMap, write the raster to disk, write the attribute data as csv file, then join your RAT to the raster using the Add Join tool in ArcMap.
Reading the definition of writeRaster writing the RAT is clearly not implemented, at least for the native and the GTif format. Actually, one of the first things done is to remove the RAT. Not too surprising given the comments in ratify() help:
The functions documented here are
mainly available such that files with a RAT can be read and
processed; currently there is not too much further support.
From and to R you can always use
save(r,file=ratRaster)
and then
load(ratRaster)
It keeps everything.

Resources