rtiffnetcdfclip

How to extract one variable while subsetting .nc files and getting output in .tiff?


I have multiple .nc files at global scale. I want to subset all the .nc files as per lat long extent of my study area and get output in .tiff format.

Spatial extent of study areas are as follows:

(7-12 degree N, 37-44 degree W)

I have written following code in R to subset one file. It is giving me a subset tiff file but with all the variables. My file has 8 variables and I want to choose only 1 variable named as for say 'x'. Could anyone please help me how can I choose the variable named as 'x'?

setwd("D:/Data/")

library(terra)    
file = rast("File1.nc")
Extent<-c(37,44, 7,12)
resize<- crop(file,Extent)

writeRaster(resize, filename='File.tif', overwrite=TRUE)

Solution

  • setwd("D:/Data/")
    
    library(raster)
    library(ncdf4)
    library(terra)    
    
    setwd("D:/Test")
    nc = nc_open("File1.nc")
    names(nc$var)
    net = raster("File1.nc", varname = "x")
    net
    extent<-c(37,44,7,12)     #Left Long, RIght Long. Lower Lat, Upper Lat
    datasubset<- crop(net,extent)
    datasubset
    writeRaster(datasubset, filename='Filenew.tif', overwrite=TRUE)