rar rar - 1 month ago 21
R Question

Error while extracting netcdf files into raster

I have many NCDF files in a folder. I try to extract them into raster brick using

raster
and
ncdf4
packages. If I separately extract each NCDF file it works. However, I try to extract all files using for loop then it gives me error.

R<-list.files("D:/Results/TimeSeries/NETCDF/")
r<-brick(paste0("D:/Results/TimeSeries/NETCDF/",R[[1]]),varname="T_min")

for(i in 2:length(R)){
r1<-brick(paste0("D:/Results/TimeSeries/NETCDF/",R[[i]]),varname="T_min")
r<-brick(r,r1)
}



Error in as.integer(nl) : cannot coerce type 'S4' to vector of type
'integer'


If I look at
r
and
r1
separately they seem to have same extent and both are raster brick type:

> r
class : RasterBrick
dimensions : 81, 81, 6561, 122 (nrow, ncol, ncell, nlayers)
resolution : 1, 1 (x, y)
extent : 0.5, 81.5, 0.5, 81.5 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : D:\Results\TimeSeries\NETCDF\timeseries_1km_2026.nc
names : X0026.05.02, X0026.05.03, X0026.05.04, X0026.05.05, X0026.05.06, X0026.05.07, X0026.05.08, X0026.05.09, X0026.05.10, X0026.05.11, X0026.05.12, X0026.05.13, X0026.05.14, X0026.05.15, X0026.05.16, ...
Date : 0026-05-02, 0026-08-31 (min, max)
varname : T_min

> r1
class : RasterBrick
dimensions : 81, 81, 6561, 122 (nrow, ncol, ncell, nlayers)
resolution : 1, 1 (x, y)
extent : 0.5, 81.5, 0.5, 81.5 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : D:\Results\TimeSeries\NETCDF\timeseries_1km_2027.nc
names : X0027.05.02, X0027.05.03, X0027.05.04, X0027.05.05, X0027.05.06, X0027.05.07, X0027.05.08, X0027.05.09, X0027.05.10, X0027.05.11, X0027.05.12, X0027.05.13, X0027.05.14, X0027.05.15, X0027.05.16, ...
Date : 0027-05-02, 0027-08-31 (min, max)
varname : T_min


Please help.

Answer

There is no need to loop, raster is vectorized, try

p <- "D:/Results/TimeSeries/NETCDF"
R <- list.files(p, pattern = "nc$")

r <- raster::stack(file.path(p, R), varname = "T_min")

If you did need to loop, I'd do it like this:

r <- raster::stack(lapply(file.path(p, R), raster::raster, varname = "T_min"))

but I don't think that's necessary.

Also note the use of file.path, and the facilities available within list.files. (Pasting text for file paths can be problematic, and is more complicated than using available functions).