 # Using for loop to indicate dataset based on its name

Hi, I currently have more than 700 matrices in my environment tab.

Each of them is large matrices, and each of them is named tmax1, tmax2, tmax3, ..., tmax365 and tmin1, tmin2, tmin3, ..., tmin365.

(FYI I got them using this code; tmax2011 is the name of the big dataset I am using)
for(i in 1:365){
nam <- paste("tmax", i, sep = "")
assign (nam, ncvar_get(tmax2011, "tmax", start = c(1,1,i), count = c(720, 360, 1)))
}
for(i in 1:365){
nam <- paste("tmin", i, sep = "")
assign (nam, ncvar_get(tmin2011, "tmin", start = c(1,1,i), count = c(720, 360, 1)))
}

I want to make 365 more matrices named tavg1, tavg2, ..., tavg365.

Each of the matrices should be average values of tmax1 and tmin1, tmax2 and tmin2, and so on.

Is there any way I can use the for loop to make these matrices?

Thanks Progress toward an answer stops here. See the FAQ

Only two 3x3 matrices are needed to illustrate the problem, but it's up to the poster to provide them.

First, R has a data structure that is much much much better suited for this kind of task: the list. You will make your life a lot easier if you just make a list `tmin` that you can index with `tmin[[i]]`. Bonus points, you can even avoid `for` loops altogether and rewrite your previous code as:

``````tmax <- lapply(1:365,
function(i) ncvar_get(tmax2011, "tmax", start = c(1,1,i), count = c(720, 360, 1)))
``````

and same for `tmin`.

That being said, to make the element-wise average of two matrices, you can simply add them (element-wise), it works:

``````
tmin1 <- matrix(1:4,2)
tmax1 <- matrix(11:14,2)

tmin1
#>      [,1] [,2]
#> [1,]    1    3
#> [2,]    2    4
tmax1
#>      [,1] [,2]
#> [1,]   11   13
#> [2,]   12   14
(tmin1 + tmax1)/2
#>      [,1] [,2]
#> [1,]    6    8
#> [2,]    7    9
``````

Created on 2020-12-10 by the reprex package (v0.3.0)

So if you switch to lists, you can use the package `purrr` to easily do the averaging for every pair of matrix:

``````library(purrr)

map2(tmin, tmax, function(A, B) (A+B)/2) # A and B are matrices extracted from the lists
``````

And if you want to stay with generating variable names on the fly, you can use `paste0()` to build an expression as a character string, then convert it to an expression with `str2expression()`, and evaluate it with `eval()`. These are advanced functionalities of the R language, that are a bit dangerous to use for routine computations.

``````eval(str2expression(paste0("(tmax", i, " + tmin", i, ")/2")))
``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.