I am using following code in R to subset a 1 .nc file while extracting 1 variable. The code is running successfully. I want to modify the existing code to input and process multiple .nc files. I tried but no success. Could anyone please help.
library(raster)
library(ncdf4)
library(terra)
setwd("D:/Test")
nc = nc_open("File1.nc")
names(nc$var)
net = raster("File1.nc", varname = "al")
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)
You can do something like this
library(terra)
inf <- list.files(pattern="\\.nc$")
outf <- gsub("\\.nc$", ".tif", inf)
e <- ext(37, 44, 7, 12)
for (i in seq_along(inf)) {
r <- rast(inf[i], "al")
re <- crop(r, e, filename=outf[i], overwrite=TRUE)
}