Skip to content

Instantly share code, notes, and snippets.

@xuanlongma
Last active March 30, 2024 20:01
Show Gist options
  • Save xuanlongma/5874674 to your computer and use it in GitHub Desktop.
Save xuanlongma/5874674 to your computer and use it in GitHub Desktop.
From netCDF to GeoTIFF using R
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
@Gilbert2015
Copy link

Hello xuanlongma. I have a Landcover data in tiff. Ho wdo i convert it to raster. Below i sthe information of the Landcover data
class : RasterLayer
dimensions : 1776, 4320, 7672320 (nrow, ncol, ncell)
resolution : 0.08333333, 0.08333333 (x, y)
extent : -180, 180, -64, 84 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /Users/gogunkoya/Downloads/LC_5min_global_2012.tif
names : LC_5min_global_2012
values : 0, 255 (min, max)

@pradhikari
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment