Last active
March 30, 2024 20:01
-
-
Save xuanlongma/5874674 to your computer and use it in GitHub Desktop.
From netCDF to GeoTIFF using R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require(ncdf) | |
require(raster) | |
## Input: a netCDF file | |
file.nc <- 'rain.nc' | |
## Output: a GeoTIFF file | |
file.tiff <- 'rain.tiff' | |
## Import netCDF | |
r.rain <- raster(file.nc) | |
## Save to disk as GeoTIFF | |
writeRaster(r.rain, filename = file.tiff, format = 'GTiff', overwrite = T) | |
## For multiple files, could use a for loop | |
## Input directory | |
dir.nc <- '/input/' | |
files.nc <- list.files(dir.nc, full.names = T, recursive = T) | |
## Output directory | |
dir.output <- '/output/' | |
## For simplicity, I use "i" as the file name, you could change any name you want, "substr" is a good function to do this. | |
for (i in 1:length(files.nc)) { | |
r.nc <- raster(files.nc[i]) | |
writeRaster(r.nc, paste(dir.output, i, '.tiff', sep = ''), format = 'GTiff', overwrite = T) | |
} | |
## END | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Xuanlongma,
I want to have a specific variable from the nc4 (e.g. GLDAS_NOAH025_M.A201106.021.nc4) in the raster. So, I modified it as
for (i in 1:length(files.nc)) {
r.nc <- raster(files.nc[i], varname="vari01")
writeRaster(r.nc, paste(dir.output, i, '.tiff', sep = ''), format = 'GTiff', overwrite = T)
}
I want the name of the output tiff file as 201106.021 (part of the name of nc4 file)_vari01.tiff. Can you please suggest me how can I do that. Thanks.