How do I stack raster files in R? - r

I am trying to perform a raster stack using three spatial raster that are in .grd format, in R using the dismo package.The three grid files are in the path "D:~" . I am using this code,
files= list.files(path = "D:~",pattern = 'grd',full.names = TRUE)
the error output am getting is
Error in x[[1]] : subscript out of bounds
Can anyone help? thanks in advance

If the files are in sub-directories then you can use recursive=TRUE:
files <- list.files(path="D:", pattern="grd", all.files=FALSE, full.names=TRUE,recursive=TRUE)
s <- stack(files)

Simply use the stack function from the raster package:
files=c("layer1.grd", "layer2.grd", "layer3.grd")
library(raster)
raster_stack=stack(files)

Related

R: Error in x[[1]] : subscript out of bounds (importing files)

I am working with the R programming language. I have a folder full of ".R" files that I want to upload into R.
The folder has the following address : C:/Users/OneDrive/Documents/dk"
I tried to follow the directions from the following tutorial: Reading in multiple .rds files and creating one object:
library(raster)
getwd()
[1] "C:/Users/OneDrive/Documents"
path = "C:/Users/OneDrive/Documents/dk"
files <- list.files(path = path, pattern = "\\.R$", full.names = TRUE)
r <- lapply(files, readRDS)
s <- stack(r)
But this returns the following error:
Error in x[[1]] : subscript out of bounds
Does anyone know what I am doing wrong? I have included a screenshot which shows the general setup:
My goal is to load all these R files into R Studio at once, and then run them all at the same time - thus, creating all these functions in the global environment.
Can someone please show me what I am doing wrong?
Thanks
You can use source to get the functions available in individual R files to the global environment.
files <- list.files(path = path, pattern = "\\.R$", full.names = TRUE)
lapply(files, source)
As suggested, the second answer from the question I linked was able to help!
files <- list.files(path = path, pattern = "\\.rds$", full.names = TRUE)
stack <- do.call("rbind", lapply(files, readRDS))

Get Raster data in right orientation

I have a problem getting raster data in the right orientation. The original raster data when imported into R looks this .
I tried using the transpose function in raster but it didn't work. The transposed data looks like this .
I used the code below. Any help or advice would be greatly appreciated. Also, is there a way to apply the plausible solution to the entire stack (all rasters are of the same extent)? Thank you.
f_PM <- list.files(path=".",
pattern='tif$', full.names=TRUE)
s_PM <- stack(f_PM) ## create a stack of the rasters
plot(s_PM[[1]]) ##check the orientation
PM <- s_PM[[1]] ## pick one raster and try to change the orientation
PM2 <- t(PM)
plot(PM2)
You need to flip then transpose:
> plot(m)
> r = t(flip(m))
> plot(r)
Note there's https://gis.stackexchange.com where spatial questions like this get asked. (Too much noise here to help with most spatial stuff).

Error in brick(file.choose()) : could not find function "brick"

I was trying to convert a dataset from netcdf to csv format using R.
although I have installed 'raster and 'netcdf4' in R.
but still it doesn't find nc.brick.
rm(list=ls())
library(raster)
library(ncdf4)
nc.brick <- brick(file.choose)
dim(nc.brick)
nc.df <- as.data.frame(nc.brick[[1]],xy=T)
head(nc.df)
write.csv(nc.df,file.choose())
test <- read.csv(file.choose())
Can you see the difference between your usage of file.choose in these two lines:
nc.brick <- brick(file.choose)
write.csv(nc.df,file.choose())
there's your problem.

What functions can be used to call information about files?

I need to get information on the extent, resolution, and cell number of the my file. I'm working with raster files.
You can do
library(raster)
# r <- raster("filename")
r <- raster()
extent(r)
ncell(r)
res(r)
You can read more about the methods in the raster package here

lapply to convert rasters to polygons using gdal_polygonizeR

I am using John Baumgrtner's gdal_polygonizeR (https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) to covert rasters to polygons in R. Aside - I tried raster pkg rasterToPolygons function and it took forever; gdal_polygonizeR is way faster. Anyways, I have a list of 533 raster files (different extents) that I want to convert to polygons. The gdal_polygonizeR function works when a single list element is called, but I have tried to use it on all list elements using lapply and get an error message. See code below:
#path to folder containing all .tif raster files
dir <- "/path/to/raster/files"
#create a list of the files in the folder
files <- list.files(path = dir, pattern = ".tif$")
#use lapply to import/create list of all files in folder
rasterl_50 <- lapply(paste0(dir, files), raster)
#test gdal_polygonizeR function on single list element
gdal_polygonizeR(rasterl_50[[1]]) #works properly
#loop thru all elements in list
lapply(rasterl_50, gdal_polygonizeR)
Output = the first six (6) elements seem to run OK, but I get the following error msg at [[7]]:
wfp1 <- gdal_polygonizeR(rasterl_50[[1]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4dc99d8d.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp2 <- gdal_polygonizeR(rasterl_50[[2]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d7698a853.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp3 <- gdal_polygonizeR(rasterl_50[[3]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d30d4d703.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp4 <- gdal_polygonizeR(rasterl_50[[4]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d24036d07.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp5 <- gdal_polygonizeR(rasterl_50[[5]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4683ed87.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp6 <- gdal_polygonizeR(rasterl_50[[6]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4e23b4d1.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp7 <- gdal_polygonizeR(rasterl_50[[7]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d6791d108.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
Error in readOGR(dirname(outshape), layer = basename(outshape), verbose = !quiet) :
no features found
In addition: Warning message:
In ogrFIDs(dsn = dsn, layer = layer) :
Show Traceback
Rerun with Debug
Error in readOGR(dirname(outshape), layer = basename(outshape), verbose = !quiet) :
no features found
#
If anyone has ideas for a solution using lapply or a for loop etc., please reply. Thanks
Solution: I had to run gdal_polygonizeR on each individual list element, and found that several raster files in the list contained no values (this resulted from reclassify function applied to rasters prior). I removed these files from the list, and lapply worked. Here is the code:
#remove 'no value' elements from the list
new_rastlist <-
rasterlist[c(-7,-14,-36,-89,-191,-310,-432,-436,-476,-493,-494,-501)]
#then try again to use lapply
polyl <- lapply(rastlist, gdal_polygonizeR)
UPDATE:
Even better, remove rasters with all NAs first with this:
batch_reclass <- function(rastlist){
for (i in 1:length(wfrastlist)) {
#read in raster
r <-raster(paste0("/path/to/rasterfiles/", rastlist[i]))
#perform the reclassifcation
rc <- reclassify(r, rclmat)
#write each reclass to a new file
if (!is.na(minValue(rc))) {
writeRaster(rc, filename = paste0("/path/to/new/rasterfiles/", "rc_",
rastlist[i]), format="GTiff", overwrite=TRUE)
}}
}
#run the function
batch_reclass(rastlist)

Resources