Question

Help a newbie out please :) I am trying to loop through rasters in a file, simply to import them into R and give them names that are taken from their file name.

I can get a string of the path names out fine

# Establish path to raster files
hab = "C:\\Michelle\\Michelle\\R\\Variables"         
hab = list.files(path = hab, full.names = T, recursive = T)  # path to each file
hab = hab[substring(hab,nchar(hab)-2,nchar(hab))=="ovr"]     # keep the raster file path

Then I've figured out how to loop through the rasters, but I can figure out how to name each one with the associated file name. I can extract the file names with the first line of code below....but the .ovr is still attached.

#Extract File names for each raster
file = unlist(lapply(hab,function(x) strsplit(x,"/")[[1]][3]))   # vector of file names
#  process each raster in HAB
for(j in 1:length(hab) ){
    a = raster(hab[j])}
Was it helpful?

Solution

Use assign but keep in mind that you can also create a raster stack or brick by passing a vector of valid rasters to the function. The original raster names are kept in the raster object. However, it is required that all of your rasters share common resolution, dimensions (row/col), extent and origin coordinates. If you want to predict a spatial model you would use this input and call predict. There is a wrapper in the raster package that will predict to a raster stack/brick object and stay memory safe. I made some suggestions to your code.

# if you set the working directory you do not need to return the full path in list.files.      
  setwd("C:/Michelle/Michelle/R/Variables")

# Use pattern arg to return a wildcard for ovr
  hab = list.files(getwd(), pattern="ovr$", full.names=FALSE) 

# Create raster stack and display associated names 
r <- stack(hab)
  names(r)   

# Here is how you return just the files names
  hab.names <- c( unlist( lapply(strsplit(hab,"[.]"), FUN=function(x) { x[1] })))   

# For loop assigning files names to individual raster objects
  for(j in 1:length(hab) ) { assign(hab.names[j], raster(hab[j]) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top