how to loop through an array in R?

38 Views Asked by At
   library(ncdf4)
   nc_data=nc_open("ncdd-195101-grd-scaled.nc")

can be found(downloaded) here: https://www.ncei.noaa.gov/data/nclimgrid-daily/access/grids/1951/ncdd-195101-grd-scaled.nc

     tas <- ncvar_get(nc_data, "tmax") 
     str(tas)
     num [1:1385, 1:596, 1:31] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ...

Extract time series for one pixel:

        gg=tas[100,245,]

I want to compute the correlation between gg and all other pixels of the file

for instance with itself

      cor(gg,gg)
      
      
      now i need with all other time series.
       
          [1, 1, ] , [1, 2, ] ,[1, 3, ], etc
      tha output will be like tas[,,1]  with correlation values.
1

There are 1 best solutions below

4
ReelSaemon On

As I understand your problem, the set of pixels is a two-dimensional array (with the time-dimension being the third).

When you want to calculate the correlations for each pixel what you would get is a correlation matrix for each pixel, not a vector of correlations.

My take on a possible solution would incorporate a loop through all pixels and a subsequent calculation of the correlation matrix.

You would have to loop through the first two dimensions (possibly with a nested for()-loop). Then calculate the correlation with each other pixel (I chose a nested lapply()-statement to save each correlation matrix as a named list element.

cors_list <- list()
for(row in 1:dim(tas)[1]) {
  for(col in 1:dim(tas)[2]) {
    
    cors_list[[paste0(row, "-", col)]] <- lapply(1:dim(tas)[1], 
                                                 function(x) lapply(1:dim(tas)[2], 
                                                 function(y) cor(tas[row, col,], tas[x, y,])))
    
  }
}