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
135 views
in Technique[技术] by (71.8m points)

r - Create a list of multiple matrices with list instead of using a for loop

I am working with a precipitation data set that is organised in an array (dimensions are 150 150 80). The third dimension respresents the single time steps. Additonally I have a matrix called "mask" of dimensions 150 150. The goal is to multiply this matrix with every single time step so that at the end there are 80 (which is equal to ntime) resulting matrices.

This can easily be done using a loop:

for (i in 1:ntime) {
  assign(paste0("matrix_out",i), PRECIPITATION[,,i]*mask)
}

The thing is that afterwards I have to deal with 80 matrices, called "matrix_out1, matrix_out1, ..., matrix_out80". It is possible to further process these data, but not very elegant though.

I am sure that there is a more handy way by using a list instead of creating 80 single objects. So far I am not so familiar with working with lists.

Does anybody can give me a hint how to do that?

question from:https://stackoverflow.com/questions/65936468/create-a-list-of-multiple-matrices-with-list-instead-of-using-a-for-loop

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

1 Reply

0 votes
by (71.8m points)

The simplest solution would be to add each loop result to a list:

matlist <- list()
for (i in 1:ntime) {
  matlist[[i]] = assign(paste0("matrix_out",i), PRECIPITATION[,,i]*mask)
}

Right, I forgot about the matrices saved to the environment. You can eliminate that with:

matlist <- list()
for (i in 1:ntime) {
  matlist[[i]] = PRECIPITATION[,,i]*mask
  names(matlist)[i] = paste0("matrix_out",i)
}

So the stand-alone matrices are not created


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

...