Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

r - How to loop over multiple lists

I am working with precipitation data for four river basins. The four rivers are Main, Danube, Isar and Inn. The precipitation data set is organised in an array (dimensions are 150 150 80). The third dimension respresents the single time steps. For every river basin I have a matrix called "mask_rivername", so "mask_Main", "mask_Danube" etc. Each matrix is of dimensions 150 150. The goal is to multiply the single matrices with every single time step of the precipitation data. To achieve this, I created a list for every river called "Main.list", "Danube.list", "Isar.list" and "Inn.list". Now I would like to fill the single lists, for example by using a loop. If I do that one by one it works well:

for (i in 1:ntime) {
  Main.list[[paste0("Main.rr",i)]] <- PRECIPITATION[,,i]*mask_Main
  Danube.list[[paste0("Danube.rr",i)]] <- PRECIPITATION[,,i]*mask_Danube
  Isar.list[[paste0("Isar.rr",i)]] <- PRECIPITATION[,,i]*mask_Isar
  Inn.list[[paste0("Inn.rr",i)]] <- PRECIPITATION[,,i]*mask_Inn
}

I am sure there must be a more elegant way, but I could not find it. My problem is that get(paste0()) does not work at the beginning of a loop.

Anybody here with a hint?

question from:https://stackoverflow.com/questions/65940328/how-to-loop-over-multiple-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...