0

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)
}

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.