简体   繁体   中英

Dynamic output file name in R

I am so close to getting my code to work, but cannot seem to figure out how to get a dynamic file name. Here is what Ivve got:

require(ncdf)
require(raster)
require(rgdal)

## For multiple files, use a for loop
## Input directory
dir.nc <- 'inputdirectoy'
files.nc <- list.files(dir.nc, full.names = T, recursive = T)

## Output directory
dir.output <- 'outputdirectory'

## For simplicity, I use "i" as the file name, but would like to have a dynamic one
for (i in 1:length(files.nc)) {
  r.nc <- raster(files.nc[i], varname = "precipitation")
  writeRaster(r.nc, paste(dir.output, i, '.tiff', sep = ''), format = 'GTiff', prj = T,  overwrite = T)
}

## END

I appreciate any help. So close!!

You can do this in different ways, but I think it is generally easiest to first create all the output filenames (and check if they are correct) and then use these in the loop.

So something like this:

library(raster)
infiles <- list.files('inputpath', full.names=TRUE)
ff <- extension(basename(infiles), '.tif')
outpath <- 'outputpath'    
outfiles <- file.path(outpath, ff)

To assure that you are writing to an existing folder, you can create it first.

dir.create(outpath, showWarnings=FALSE, recursive=TRUE)

And then loop over the files

for (i in 1:length(infiles)) {
  r  <- raster(infiles[i])
  writeRaster(r, paste(outfiles[i],  overwrite = TRUE)
}

You might also use something along these lines

outfiles <- gsub('in', 'out', infiles) 

Here is the code that finally worked:

# Imports
library(raster)

#Set source file
infiles <- list.files('infilepath', full.names=TRUE)

#create dynamic file names and choose outfiles to view list
ff <- extension(basename(infiles), '.tif')
outpath <- 'outfilepath'    
outfiles <- file.path(outpath, ff)

#run da loop
for (i in 1:length(infiles)) {
  r  <- raster(infiles[i])
  writeRaster(r, paste(outfiles[i]), format ='GTiff', overwrite = T)
}

## END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM