The question can be answered the R way with a double lapply
loop. As long as both arguments, the precipitation array and the masks are in list objects. That's what the preliminary code does, to create two lists.
mask_list <- mget(ls(pattern = "^mask_", envir = .GlobalEnv), envir = .GlobalEnv)
nmat <- dim(PRECIPITATION)[3]
precip_list <- lapply(seq.int(nmat), function(i) PRECIPITATION[,, i])
new_precip <- lapply(mask_list, function(x, y){
lapply(y, function(.y) .y * x)
}, y = precip_list)
rivers <- sub("^mask_", "", names(mask_list))
new_precip <- lapply(seq_along(new_precip), function(i){
names(new_precip[[i]]) <- paste(rivers[i], seq.int(nmat), sep = ".")
new_precip[[i]]
})
names(new_precip) <- rivers
To have this result as lists in the .GlobalEnv
, you can use list2env
.
Test data
PRECIPITATION <- array(-199:200, dim = c(10, 10, 4))
mask_Main <-
mask_Danube <-
mask_Isar <-
mask_Inn <- matrix(-1:1, nrow = 10, ncol = 10)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…