Reputation: 21
I am a new programmer. Recently I was given 1,850 .nc files which I subsetted to 480 files. Each filename has a number to indicate the month. All I want to do is:
I know this shouldn't be difficult but I am having trouble. So far I haven't gotten past step 2:
library(RNetCDF)
library(raster)
library(rgdal)
files=list.files(pattern='*.nc', full.names=TRUE)
for (i in seq_along(files)){
nc=open.nc(files[i])}
list(nc)
for(i in 1:length(nc)){
rnc<-raster(nc[i])
writeRaster(rnc, filename=names(rnc), bylayer=TRUE, format="GTiff")}
As you all can tell, I am still a newbie/student of R, I think I have step 1 OK, the for loop for step 2 does not seem to be working. Once I get 1 and 2 completed, I can work on 3 (if you all can see an easy answer for step 3 please share).
Thank you.
Upvotes: 1
Views: 1098
Reputation: 47146
You can do something like this:
library(raster)
library(ncdf4)
files <- list.files(pattern='*.nc', full.names=TRUE)
Either:
s <- stack(files)
rnc <- writeRaster(s, filename="x", bylayer=TRUE, format="GTiff")}
Or with a loop:
for (f in files) {
r <- raster(f)
fout <- extension(f, '.tif')
r <- writeRaster(r, filename=fout, datatype='FLT4S')
}
To get monthly averages, you can do something like:
months <- stackApply(s, 1:12, mean)
Assuming that the files are in the right order.
Upvotes: 3