Shoaib Ali
Shoaib Ali

Reputation: 1

I have 163 raster files want to aggregate from 50 km to 100 km resolution using for loop. please guide me. thanks

library(raster)
library(stringr)
setwd("file.choose")
tws50km =list.files(pattern=".tif",full.names = F)
time_list <- str_sub(gsub("-", "", seq(as.Date("2002/4/1"), by = "month", length.out = 163)), 1,6)

for (i in 1:length(tws50km)){
   tws100km = aggregate(i, fact = 2, fun = mean)
   writeRaster(tws100km,paste('tws_',time_list[i], ".tif", sep = " "), "GTiff", overwrite=TRUE) 
}

Error in match.fun(FUN) : argument "FUN" is missing, with no default

Upvotes: 0

Views: 182

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47146

It should be something like this

library(raster)
inf <- list.files(pattern=".tif",full.names = F)

It is easiest to make all output filenames in step, as I show below. But what you are doing does not look good. How do you know that you are using the right filename, that they match the data? You would normally change the input filenames inf in some way. But I cannot improve your approach as you do not shown any input file names.

outf <- substr(gsub("-", "", seq(as.Date("2002/4/1"), by="month", length.out=163)), 1,6)
# use paste0, avoid spaces in filenames
outf <- paste0('tws_', outf, ".tif")
outf[1:2]
#[1] "tws_200204.tif" "tws_200205.tif"

Now loop. First create a RasterLayer with raster (or use brick if there multiple layers), then aggregate that object (you cannot aggregate a filename!). No need for writeRaster as aggregate has its own filename argument.

for (i in 1:length(inf)) {
    r <- raster(inf[i])
    x <- aggregate(r, fact=2, fun=mean, filename=outf[i], overwrite=TRUE) 
}

Upvotes: 2

Chris
Chris

Reputation: 2286

Your date code is just fine and I wasn't thinking fully when I commented, but you need to progressively update everything as you go through your loop, so we'll put [i] everywhere that things are going from 1-2-3~163

library(raster)
library(stringr)
setwd("file.choose")
tws50km =list.files(pattern=".tif",full.names = F)

I did change time_list to time_month both here and in the loop because in the future you'll want to know that this is a character vector accessed by [, and not a list accessed by [[

time_month <- str_sub(gsub("-", "", seq(as.Date("2002/4/1"), by = "month", length.out = 163)), 1,6)

So just copying your for loop and thinking [i]:

for (i in 1:length(tws50km)){
   tws100km[i] = aggregate(tws50km[i], fact = 2, fun = mean)
   writeRaster(tws100km[i],paste('tws_',time_month[i], ".tif", sep = " "), "GTiff", overwrite=TRUE) 
}

and hopefully this does it.

Upvotes: 1

Related Questions