user2807119
user2807119

Reputation: 353

Not saving output raster file name as set in input file list

When ESRI grid file format rasters are read into for loop and convert them to HFA files, output file name is not set as same as the input file name. Following code is used for the conversion;

library(raster)
raster_data <- list.files(pattern='rain', full.names=FALSE)

# "rain1970" "rain1971"

for (i in 1:length(raster_data)) {
    r.nc <- raster(raster_data[i])
    writeRaster(r.nc, paste0(i, '.IMG', sep = ''), format = 'HFA', overwrite = T)
}

Upvotes: 0

Views: 103

Answers (1)

rosscova
rosscova

Reputation: 5580

The value i in your for loop is an integer, iterated as per your 1:length(raster_data) input. You need to reference the name from your raster_data vector using that integer, rather than pasting the integer itself.

Change this:

paste0(i, '.IMG', sep = '')

To this:

paste0(raster_data[i], '.IMG', sep = '')

Now you're getting the text string at location i within your input list. You'll probably want to remove the original file extension though, so maybe this would work better.

sub( "\\.[a-z|A-Z]+$", ".IMG", raster_data[i] )

This will replace any existing file extension with your new one.

Upvotes: 0

Related Questions