3

I've downloaded 6 multi-band raster files (each file has 4 bands) from the National Weather Service containing precipitation data for different time periods (30, 60, 90, 120, and 365 day periods). Here's where I downloaded the data from: https://water.weather.gov/precip/download.php

I want to write a loop to pull each of those files into R, with each raster band assigned to a different variable. Here's an example for just one raster file for the 30 day time period:

library(rgdal)
library(raster)

y <- format(Sys.Date()-1,"%Y")
m <- format(Sys.Date()-1,"%m")
d <- format(Sys.Date()-1,"%d")

NWS1_prev30 <- raster(paste0('/path/nws_precip_last30days_', y, m, d, '_conus.tif'), band = 1)
NWS2_prev30 <- raster(paste0('/path/nws_precip_last30days_', y, m, d, '_conus.tif'), band = 2)
NWS3_prev30 <- raster(paste0('/path/nws_precip_last30days_', y, m, d, '_conus.tif'), band = 3)
NWS4_prev30 <- raster(paste0('/path/nws_precip_last30days_', y, m, d, '_conus.tif'), band = 4)

I don't really want to copy and paste that 5 other times, so was hoping to write a loop. However, I'm receiving an error with my code as it is so far. Here's what I have:

pathname <- c(paste0("/path/nws_precip_last30days_", y, m, d, "_conus.tif"),paste0("/path/nws_precip_last60days_", y, m, d,"_conus.tif"),paste0("/path/nws_precip_last9days_", y, m, d,"_conus.tif"),paste0("path//nws_precip_last120days_", y, m, d,"_conus.tif"), 
              paste0("/path/nws_precip_last180days_", y, m, d,"_conus.tif"), paste0("/path/nws_precip_last120days_", y, m, d,"_conus.tif"), paste0("/path/nws_precip_last365days_", y, m, d,"_conus.tif"))

# Bulk
for (j in 1:length(pathname)) {
  for (k in 1:4) {
    assign(paste0("NWS", k, j), raster(j, band = k))
  }
}

# Error in (function (classes, fdef, mtable)  : 
#  unable to find an inherited method for function ‘raster’ for signature ‘"integer"’

0

Right now you're trying to load a raster using j - which is just an integer. Instead, you want to load it from the selection of path names. So, if you use indexing:

for (j in 1:length(pathname)) {
  for (k in 1:4) {
    assign(paste0("NWS", k, j), raster(pathname[j], band = k))
  }
}

you may have better luck.

1
  • That was definitely the issue - thank you! – happymappy Oct 28 '19 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.